feat: preloading JavaScript files (#1189)

close #1187

## points

- use `<link rel="modulepreload">` tag and `Link: rel="modulepreload"`
header to preload dependencies
- No preloading at all for pages that don't use JavaScript at all.
- Information about preloading is delivered only when the JS file has
already been built. If the JS file hasn't finished building, it will
respond without preload information instead of waiting for the build and
then returning the HTML.

## performance comparison

I've deployed this branch to https://fresh-module-preload.deno.dev/ so
you can try it out and see how it behaves.

When I accessed [fresh.deno.dev](https://fresh.deno.dev/) and
[fresh-module-preload.deno.dev](https://fresh-module-preload.deno.dev/)
20 times each and measured the DOMContentLoaded time, it was 24% faster
(157.3ms -> 118.95ms) in my environment (Nagano City, Japan).

<details>
<summary>Actual measured data</summary>

(Don't forget to check `Disable Cache` in devtools)

 | afeter (ms) | before (ms)
-- | -- | --
0 | 180 | 152
1 | 82 | 144
2 | 78 | 186
3 | 156 | 196
4 | 88 | 211
5 | 85 | 123
6 | 162 | 209
7 | 154 | 110
8 | 86 | 175
9 | 135 | 109
10 | 183 | 117
11 | 115 | 159
12 | 99 | 173
13 | 83 | 131
14 | 82 | 142
15 | 135 | 160
16 | 120 | 125
17 | 148 | 152
18 | 118 | 229
19 | 90 | 143
average | 118.95 | 157.3

</details>

## screen shots


![image](https://github.com/denoland/fresh/assets/40050810/c8f6d46b-77da-4e20-b29c-3b0219907872)


![image](https://github.com/denoland/fresh/assets/40050810/3159904c-07f0-45ee-a9ca-7bed35a292ca)

---------

Co-authored-by: Luca Casonato <hello@lcas.dev>
This commit is contained in:
ayame113
2023-06-01 11:18:28 +10:00
committed by GitHub
co-authored by Luca Casonato
parent b558b6e759
commit 7b35cb07d4
4 changed files with 21 additions and 20 deletions
+9 -12
View File
@@ -52,6 +52,7 @@ export class Bundler {
#plugins: Plugin[];
#cache: Map<string, Uint8Array> | Promise<void> | undefined = undefined;
#dev: boolean;
dependencyMap = new Map<string, string[]>();
constructor(
islands: Island[],
@@ -124,15 +125,15 @@ export class Bundler {
jsx: JSX_RUNTIME_MODE[this.#jsxConfig.jsx],
jsxImportSource: this.#jsxConfig.jsxImportSource,
});
const metafileOutputs = bundle.metafile!.outputs;
// const metafileOutputs = bundle.metafile!.outputs;
// for (const path in metafileOutputs) {
// const meta = metafileOutputs[path];
// const imports = meta.imports
// .filter(({ kind }) => kind === "import-statement")
// .map(({ path }) => `/${path}`);
// this.#preloads.set(`/${path}`, imports);
// }
for (const path in metafileOutputs) {
const meta = metafileOutputs[path];
const imports = meta.imports
.filter(({ kind }) => kind === "import-statement")
.map(({ path }) => `/${path}`);
this.dependencyMap.set(`/${path}`, imports);
}
const cache = new Map<string, Uint8Array>();
const absDirUrlLength = toFileUrl(absWorkingDir).href.length;
@@ -161,10 +162,6 @@ export class Bundler {
const cache = await this.cache();
return cache.get(path) ?? null;
}
// getPreloads(path: string): string[] {
// return this.#preloads.get(path) ?? [];
// }
}
function buildIdPlugin(buildId: string): esbuildTypes.Plugin {
+2 -6
View File
@@ -503,14 +503,13 @@ export class ServerContext {
);
}
const preloads: string[] = [];
const resp = await internalRender({
route,
islands: this.#islands,
plugins: this.#plugins,
app: this.#app,
imports,
preloads,
dependencyMap: this.#bundler.dependencyMap,
renderFn: this.#renderFn,
url: new URL(req.url),
params,
@@ -541,10 +540,7 @@ export class ServerContext {
status: options?.status ?? status,
statusText: options?.statusText,
headers: options?.headers
? {
...headers,
...options.headers,
}
? { ...headers, ...options.headers }
: headers,
});
};
+9 -2
View File
@@ -26,7 +26,7 @@ export interface RenderOptions<Data> {
plugins: Plugin[];
app: AppModule;
imports: string[];
preloads: string[];
dependencyMap: Map<string, string[]>;
url: URL;
params: Record<string, string | string[]>;
renderFn: RenderFunction;
@@ -209,6 +209,7 @@ export async function render<Data>(
bodyHtml = bodyHtml as string;
const imports: [string, string][] = [];
const preloadSet = new Set<string>();
function addImport(path: string): string {
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
@@ -219,6 +220,11 @@ export async function render<Data>(
}
const url = bundleAssetUrl(path);
imports.push([url, randomNonce]);
preloadSet.add(url);
for (const depPath of opts.dependencyMap.get(path) ?? []) {
const url = bundleAssetUrl(depPath);
preloadSet.add(url);
}
return url;
}
@@ -332,11 +338,12 @@ export async function render<Data>(
headComponents.splice(0, 0, node);
}
const preloads = [...preloadSet];
const html = template({
bodyHtml,
headComponents,
imports,
preloads: opts.preloads,
preloads,
lang: ctx.lang,
});
+1
View File
@@ -44,6 +44,7 @@ Deno.test("/ page prerender", async () => {
body,
`<meta name="description" content="Hello world!" />`,
);
assertStringIncludes(body, `<link rel="modulepreload"`);
});
Deno.test("/props/123 page prerender", async () => {