-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreload.tsx
40 lines (37 loc) · 1.05 KB
/
preload.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { createContext, use } from "react";
import { preloadModule, type PreloadModuleOptions } from "react-dom";
import { generateHashedName } from "./hash";
// @ignore
export const MetaContext = createContext<{
hash: Record<string, string>;
dependencies: Record<string, string[]>;
}>({ hash: {}, dependencies: {} });
function* walkDependencies(
target: string,
dependencies: Record<string, string[]>
): Generator<string> {
if (dependencies[target]) {
for (const dep of dependencies[target]) {
yield dep;
yield* walkDependencies(dep, dependencies);
}
}
}
export function PreloadModule({
module,
...options
}: { module: string } & Partial<PreloadModuleOptions>) {
if (typeof window === "undefined") {
try {
const meta = use(MetaContext);
preloadModule(generateHashedName(module, meta.hash), {
as: "script",
...options,
});
for (const dep of walkDependencies(module, meta.dependencies)) {
preloadModule(dep, { as: "script", ...options });
}
} catch {}
}
return null;
}