Files
skills/docs/foundation/data/packer-browser/src/preload/preload.md
2026-05-29 08:20:56 +01:00

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: true selection (default) or descending-priority top-N
  • Stable tiebreak for ties: lexicographic ordering on url
  • as defaults to "fetch" when absent — preserves correct dispatch
  • crossOrigin pass-through to the emitted <link>
  • OTel fetchTotal increments 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 default preload: true filter
    • opts.observability?: PackerBrowserObservability — emit counters
  • injectPreloadHints(doc, hints): readonly HTMLLinkElement[]

    • Returns [] when doc is undefined or has no <head>.
    • Each created element carries rel="preload", the configured href, as, and optional crossorigin attributes.

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.
  • topN is 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.
  • injectPreloadHints does not handle the non-DOM environment by feature-flag; it relies on doc === undefined or doc.head === null so a hand-rolled adapter can drop a fake document in tests.