perf: add loading optimization with modulepreload (#15)

This commit aims to speed up loading of chunked modules using
the link rel=modulepreload directive.
This commit is contained in:
Luca Casonato
2021-06-02 12:55:30 +02:00
committed by GitHub
parent 26189cfdf3
commit 41307a5ac8
3 changed files with 54 additions and 10 deletions
+16
View File
@@ -18,6 +18,7 @@ async function ensureEsbuildInialized() {
export class Bundler { export class Bundler {
#pages: Page[]; #pages: Page[];
#cache: Map<string, Uint8Array> | Promise<void> | undefined = undefined; #cache: Map<string, Uint8Array> | Promise<void> | undefined = undefined;
#preloads = new Map<string, string[]>();
constructor(pages: Page[]) { constructor(pages: Page[]) {
this.#pages = pages; this.#pages = pages;
@@ -42,10 +43,21 @@ export class Bundler {
outfile: "", outfile: "",
jsxFactory: "h", jsxFactory: "h",
jsxFragment: "Fragment", jsxFragment: "Fragment",
metafile: true,
outdir: `/`, outdir: `/`,
entryPoints, entryPoints,
}); });
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);
}
const cache = new Map<string, Uint8Array>(); const cache = new Map<string, Uint8Array>();
for (const file of bundle.outputFiles) { for (const file of bundle.outputFiles) {
cache.set(file.path, file.contents); cache.set(file.path, file.contents);
@@ -69,6 +81,10 @@ export class Bundler {
const cache = await this.cache(); const cache = await this.cache();
return cache.get(path) ?? null; return cache.get(path) ?? null;
} }
getPreloads(path: string): string[] {
return this.#preloads.get(path) ?? [];
}
} }
function freshPlugin(pageList: Page[]): esbuild.Plugin { function freshPlugin(pageList: Page[]): esbuild.Plugin {
+26 -5
View File
@@ -1,12 +1,33 @@
import { renderToString } from "./deps.ts"; import { renderToString } from "./deps.ts";
import * as rt from "../runtime/deps.ts"; import * as rt from "../runtime/deps.ts";
import { Page } from "./routes.ts"; import { Page } from "./routes.ts";
import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts";
export function render(page: Page, params: Record<string, string>): string { export function render(
page: Page,
imports: string[],
preloads: string[],
params: Record<string, string>,
): string {
const props = { params }; const props = { params };
const propsStr = JSON.stringify(props);
const body = renderToString(rt.h(page.component, props)); const body = renderToString(rt.h(page.component, props));
return `<!DOCTYPE html><html><head><script src="${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/${page.name}.js" type="module"></script></head><body>${body}<script id="__FRSH_PROPS" type="application/json">${ return `<!DOCTYPE html>
JSON.stringify(props) <html>
}</script></body></html>`; <head>
${
preloads.map((src) => `<link rel="modulepreload" href="${src}">`).join(
"\n ",
)
}
${
imports.map((src) => `<script src="${src}" type="module"></script>`).join(
"\n ",
)
}
</head>
<body>
${body}
<script id="__FRSH_PROPS" type="application/json">${propsStr}</script>
</body>
</html>`;
} }
+12 -5
View File
@@ -10,11 +10,16 @@ export function installRoutes(
pages: Page[], pages: Page[],
apiRoutes: ApiRoute[], apiRoutes: ApiRoute[],
) { ) {
const bundler = new Bundler(pages);
for (const page of pages) { for (const page of pages) {
const bundlePath = `/${page.name}.js`;
const imports = [bundleAssetUrl(bundlePath)];
router.get<Record<string, string>>(page.route, (ctx) => { router.get<Record<string, string>>(page.route, (ctx) => {
ctx.response.status = 200; ctx.response.status = 200;
ctx.response.type = "html"; ctx.response.type = "html";
ctx.response.body = render(page, ctx.params); const preloads = bundler.getPreloads(bundlePath).map(bundleAssetUrl);
ctx.response.body = render(page, imports, preloads, ctx.params);
}); });
} }
@@ -22,7 +27,7 @@ export function installRoutes(
router.all(apiRoute.route, apiRoute.handler); router.all(apiRoute.route, apiRoute.handler);
} }
const internal = internalRouter(pages); const internal = internalRouter(bundler);
router.use( router.use(
INTERNAL_PREFIX, INTERNAL_PREFIX,
@@ -31,13 +36,15 @@ export function installRoutes(
); );
} }
function bundleAssetUrl(path: string) {
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
}
/** /**
* Returns a router that contains all fresh routes. Should be mounted at * Returns a router that contains all fresh routes. Should be mounted at
* constants.INTERNAL_PREFIX * constants.INTERNAL_PREFIX
*/ */
function internalRouter(pages: Page[]): oak.Router { function internalRouter(bundler: Bundler): oak.Router {
const bundler = new Bundler(pages);
const router = new oak.Router(); const router = new oak.Router();
router.get(`${JS_PREFIX}/${BUILD_ID}/:path*`, async (ctx) => { router.get(`${JS_PREFIX}/${BUILD_ID}/:path*`, async (ctx) => {