3.0 KiB
3.0 KiB
preload — <link rel="preload"> hint generation
(no submodules)
Purpose
generatePreloadHints derives an ordered list of <link rel="preload">
hints from a packed manifest, and injectPreloadHints appends those
hints to a document's <head>. Together they let the Service Worker
(or a one-off bootstrap script) preload critical packed entries before
the browser's HTML parser would have requested them.
These helpers are PACKER-BROWSER-18's production surface. They are pure
and feature-detected — injectPreloadHints is safe to call from a
Service Worker context (document is undefined) and will simply
return an empty array.
Features
preload: trueselection (default) or descending-priority top-N- Stable tiebreak for ties: lexicographic ordering on
url asdefaults to"fetch"when absent — preserves correct dispatchcrossOriginpass-through to the emitted<link>- OTel
fetchTotalincrements when an observability bundle is supplied
Usage: Basic
import {
generatePreloadHints,
injectPreloadHints,
} from "@suaveplan/packer-browser/preload";
const hints = generatePreloadHints({
entries: [
{ url: "/hero.image.packed", preload: true, as: "image" },
{ url: "/font.woff2", preload: true, as: "font" },
],
});
injectPreloadHints(document, hints);
Usage: Advanced
import { createPackerBrowserObservability } from "@suaveplan/packer-browser";
const observability = createPackerBrowserObservability({ meter });
const topThree = generatePreloadHints(
{
entries: [
{ url: "/a.packed", priority: 1 },
{ url: "/b.packed", priority: 5 },
{ url: "/c.packed", priority: 3 },
],
},
{ topN: 3, observability }
);
// emits 3 fetchTotal increments
API Reference
-
generatePreloadHints(manifest, opts?): readonly PreloadHintLink[]manifest.entries: ReadonlyArray<PreloadManifestEntry>opts.topN?: number— override the defaultpreload: truefilteropts.observability?: PackerBrowserObservability— emit counters
-
injectPreloadHints(doc, hints): readonly HTMLLinkElement[]- Returns
[]whendocisundefinedor has no<head>. - Each created element carries
rel="preload", the configuredhref,as, and optionalcrossoriginattributes.
- Returns
Implementation Notes
- The OTel emission is intentionally one counter per emitted hint — not one per manifest entry — so the count tracks bytes that actually get preload-requested by the browser.
topNis clamped to[0, manifest.entries.length]so a negative value yields an empty array without throwing.- The helper does not de-duplicate URLs — manifests are the source of truth for ordering and duplicates.
injectPreloadHintsdoes not handle the non-DOM environment by feature-flag; it relies ondoc === undefinedordoc.head === nullso a hand-rolled adapter can drop a fake document in tests.