diff --git a/src/context.ts b/src/context.ts index 4a54428f..f9b0d778 100644 --- a/src/context.ts +++ b/src/context.ts @@ -14,6 +14,7 @@ import { setRenderState, } from "./runtime/server/preact_hooks.tsx"; import { DEV_ERROR_OVERLAY_URL } from "./constants.ts"; +import { asset } from "./runtime/shared.ts"; export interface Island { file: string | URL; @@ -188,6 +189,7 @@ export class FreshReqContext this.#islandRegistry, this.#buildCache, partialId, + headers, ); return new Response(html, responseInit); } @@ -211,6 +213,7 @@ function preactRender( islandRegistry: ServerIslandRegistry, buildCache: BuildCache, partialId: string, + headers: Headers, ) { const state = new RenderState(ctx, islandRegistry, buildCache, partialId); setRenderState(state); @@ -234,6 +237,23 @@ function preactRender( return `${res}`; } finally { + // Add preload headers + const basePath = ctx.config.basePath; + const runtimeUrl = asset(`${basePath}/fresh-runtime.js`); + let link = `<${encodeURI(runtimeUrl)}>; rel="modulepreload"; as="script"`; + state.islands.forEach((island) => { + const chunk = buildCache.getIslandChunkName(island.name); + if (chunk !== null) { + link += `, <${ + encodeURI(asset(`${basePath}${chunk}`)) + }>; rel="modulepreload"; as="script"`; + } + }); + + if (link !== "") { + headers.append("Link", link); + } + state.clear(); setRenderState(null); } diff --git a/tests/islands_test.tsx b/tests/islands_test.tsx index 055a7c06..fdf4a341 100644 --- a/tests/islands_test.tsx +++ b/tests/islands_test.tsx @@ -30,6 +30,7 @@ import { setBuildCache } from "../src/app.ts"; import { getBuildCache } from "../src/app.ts"; import type { FreshConfig } from "../src/config.ts"; import { FreshAttrs } from "./fixtures_islands/FreshAttrs.tsx"; +import { FakeServer } from "../src/test_utils.ts"; await buildProd(allIslandApp); @@ -659,3 +660,29 @@ Deno.test({ }); }, }); + +Deno.test({ + name: "islands - adds preload HTTP headers", + fn: async () => { + const selfCounter = getIsland("SelfCounter.tsx"); + + const app = testApp() + .use(staticFiles()) + .island(selfCounter, "SelfCounter", SelfCounter) + .get("/", (ctx) => + ctx.render( + + + , + )); + + const server = new FakeServer(await app.handler()); + const res = await server.get("/"); + await res.body?.cancel(); + + const link = res.headers.get("Link"); + expect(link).toMatch( + /<\/fresh-runtime\.js\?__frsh_c=[^>]+>; rel="modulepreload"; as="script", <\/SelfCounter\.js\?__frsh_c=[^>]+>; rel="modulepreload"; as="script"/, + ); + }, +}); diff --git a/tests/test_utils.tsx b/tests/test_utils.tsx index e1ef222b..af42e35c 100644 --- a/tests/test_utils.tsx +++ b/tests/test_utils.tsx @@ -162,7 +162,7 @@ export async function withChildProcessServer( } if (!found) { - throw new Error(`Could not find server addrews`); + throw new Error(`Could not find server address`); } try {