src/lib/perf/font-preloads.ts
Linked repository file from this build.
/** React/Next can move resource hints from HTML into HTTP Link headers. Count both. */
export function fontPreloads(html: string, linkHeader = ""): string[] {
const urls = new Set<string>();
for (const tag of html.match(/<link\b[^>]*>/gi) ?? []) {
const attributes = Object.fromEntries(
[...tag.matchAll(/([\w-]+)\s*=\s*(["'])(.*?)\2/g)].map((match) => [
match[1].toLowerCase(),
match[3],
]),
);
if (
attributes.rel?.split(/\s+/).includes("preload") &&
attributes.as === "font" &&
attributes.href
)
urls.add(attributes.href);
}
for (const match of linkHeader.matchAll(/<([^>]+)>([^<]*)/g)) {
const attributes = match[2].replaceAll('"', "");
if (
/;\s*rel=preload\s*(?:;|,|$)/i.test(attributes) &&
/;\s*as=font\s*(?:;|,|$)/i.test(attributes)
)
urls.add(match[1]);
}
return [...urls];
}