Skip to content

Commit ace227e

Browse files
authored
feat(web): support responsive image preloads (#3183)
* docs(web): restore the AssetManifest note and frames budget rationale * fix(web): canonicalize resource identity qualifiers * feat(web): support responsive image preloads * fix(web): canonicalize preload identity across registration & adoption
1 parent c62aa9a commit ace227e

13 files changed

Lines changed: 1093 additions & 56 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
Canonicalize resource identity qualifiers instead of comparing raw prop values, so two declarations of one request dedupe to one `<link>` on both sides of hydration.
6+
7+
`false` now means absent, matching both attribute writers: `crossorigin={cond && "anonymous"}` no longer emits a second, byte-identical link when the condition is false.
8+
9+
`crossorigin` is compared by its CORS state rather than its spelling. It is a CORS settings attribute with three states — absent is No CORS, `use-credentials` (ASCII case-insensitive) is Use Credentials, and every other present value including `""`, a bare attribute and an invalid one is Anonymous — so the same font is no longer preloaded once per spelling, and the client adopts the server's link instead of mounting a second one for a request the browser already has.
10+
11+
Qualifier values are length-prefixed, so a value containing the identity delimiters can no longer collide with a different qualifier set and silently suppress another resource (`type: "a:media=b"` and `type: "a", media: "b"` were one identity).
12+
13+
Client-side adoption of a mount-once head resource now matches a server-emitted element on the full request identity rather than the href alone: two preloads sharing an href still differ if their destination, CORS mode, type, media or source set differ. The document client, the standalone frame client and the server all apply the same rules.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
Support `imagesrcset` and `imagesizes` in typed image preloads, including the standard form without `href`. Candidate URLs inside `imagesrcset` must already be resolved by the integration.
6+
7+
The responsive pair is image-only. On any other destination the attribute is dropped and the link still ships — an integration that computes `imagesrcset` for every asset keeps its script and style preloads. An empty or non-string value counts as absent for the same reason, so a source set is never emitted as garbage the browser cannot parse. A descriptor whose only source was such a filtered attribute is dropped entirely rather than emitted as a `<link rel="preload">` with nothing to fetch.
8+
9+
`mountHeadResource` can adopt a source-set link: it has no href, so it matches a server-emitted link on a null href plus the identity qualifiers — the rule the frame client already applied.
10+
11+
Development builds warn when `imagesrcset` uses a width descriptor without `imagesizes` (the source size falls back to `100vw`, so the preload can miss the image the `<img>` selects), and when a manifest source set carries a relative candidate — candidates are not joined with `_base`, so they resolve against the document URL whichever base the manifest declares. That check walks the source set the way the spec's parser does, so commas inside a candidate URL are not mistaken for candidate separators.

‎packages/web/frames/src/frame-client.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ export type FrameChunk =
4848
modules?: string[];
4949
styles?: string[];
5050
inlineStyles?: { id: string; content?: string; attrs?: Record<string, string> }[];
51-
preloads?: { href: string; attrs: Record<string, string> }[];
51+
preloads?: { href?: string; attrs: Record<string, string> }[];
5252
}
5353
| { type: "slot"; id: string; version: number; key: string; args: Record<string, unknown> }
5454
| { type: "complete"; id: string; version: number }
@@ -2061,14 +2061,33 @@ function parseFragment(html) {
20612061
// Mirrors head.ts without importing it into the standalone frame client.
20622062
const PRELOAD_QUALIFIERS = ["as", "crossorigin", "type", "media", "imagesrcset", "imagesizes"];
20632063

2064+
// Mirrors head.ts's qualifierValue — keep them in step. `as` folds ASCII
2065+
// case; an empty source set or size reads as absent (registration never
2066+
// emits one); `crossorigin` is three states, not a string range, so `""`, a
2067+
// bare attribute and `anonymous` are one request. Frame `attrs` are already
2068+
// canonical strings, but the document may carry any spelling.
2069+
function qualifierValue(name, value) {
2070+
if (value == null) return null;
2071+
if (name === "imagesrcset" || name === "imagesizes") return value === "" ? null : value;
2072+
if (name === "as") return value.replace(/[A-Z]/g, c => String.fromCharCode(c.charCodeAt(0) + 32));
2073+
if (name !== "crossorigin") return value;
2074+
return value.length === 15 && value.toLowerCase() === "use-credentials"
2075+
? "use-credentials"
2076+
: "anonymous";
2077+
}
2078+
20642079
/** Attribute-compared head lookup so href/id values never need escaping. */
20652080
function findHeadElement(selector, attr, value, qualifiers) {
20662081
candidate: for (const node of document.head.querySelectorAll(selector)) {
20672082
if (node.getAttribute(attr) !== value) continue;
20682083
if (!qualifiers) return node;
20692084
for (let i = 0; i < PRELOAD_QUALIFIERS.length; i++) {
20702085
const name = PRELOAD_QUALIFIERS[i];
2071-
if (node.getAttribute(name) !== (qualifiers[name] ?? null)) continue candidate;
2086+
if (
2087+
qualifierValue(name, node.getAttribute(name)) !==
2088+
qualifierValue(name, qualifiers[name] ?? null)
2089+
)
2090+
continue candidate;
20722091
}
20732092
return node;
20742093
}
@@ -2078,11 +2097,12 @@ function findHeadElement(selector, attr, value, qualifiers) {
20782097
/** Ensure one typed preload exists, preserving request-qualifying attributes. */
20792098
function ensurePreload(entry) {
20802099
const attrs = entry.attrs;
2081-
if (findHeadElement('link[rel="preload"]', "href", entry.href, attrs)) return;
2100+
const href = entry.href;
2101+
if (findHeadElement('link[rel="preload"]', "href", href || null, attrs)) return;
20822102
const link = document.createElement("link");
20832103
link.rel = "preload";
20842104
for (const name in attrs) link.setAttribute(name, attrs[name]);
2085-
link.setAttribute("href", entry.href);
2105+
if (href) link.setAttribute("href", href);
20862106
document.head.appendChild(link);
20872107
}
20882108

‎packages/web/frames/src/frame-sink.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ export {
171171
} from "./frame-transport.js";
172172

173173
function wirePreload(entry) {
174-
return { href: entry.href, attrs: entry.attrs };
174+
return entry.href ? { href: entry.href, attrs: entry.attrs } : { attrs: entry.attrs };
175175
}
176176

177177
/**

‎packages/web/src/client.ts‎

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,8 @@ import {
134134
resourceIdentity,
135135
replaceableIdentity,
136136
resolveHead,
137+
RESOURCE_QUALIFIERS,
138+
qualifierValue,
137139
STYLESHEET_FETCH_META
138140
} from "./head.js";
139141
export {
@@ -1031,10 +1033,25 @@ function assetEntryKey(descriptor) {
10311033

10321034
// Attribute-compared lookup (instead of an attribute selector) so href/id
10331035
// values never need selector escaping.
1034-
function findAssetElement(selector, attr, value) {
1036+
// `qualifiers` narrows a match to the same request: two preloads sharing an
1037+
// href still differ if their destination, CORS mode or source set differ, so
1038+
// adopting across them would drop a link the server meant to emit. Both sides
1039+
// go through `qualifierValue`, the same canonicalization the identity uses —
1040+
// a server-emitted `crossorigin=""` and an authored `crossorigin="anonymous"`
1041+
// are one request, so adoption must see them as one.
1042+
function findAssetElement(selector, attr, value, qualifiers) {
10351043
const nodes = document.querySelectorAll(selector);
1036-
for (let i = 0; i < nodes.length; i++) {
1037-
if (nodes[i].getAttribute(attr) === value) return nodes[i];
1044+
outer: for (let i = 0; i < nodes.length; i++) {
1045+
if (nodes[i].getAttribute(attr) !== value) continue;
1046+
if (!qualifiers) return nodes[i];
1047+
for (let q = 0; q < RESOURCE_QUALIFIERS.length; q++) {
1048+
const name = RESOURCE_QUALIFIERS[q];
1049+
if (
1050+
qualifierValue(name, qualifiers[name]) !== qualifierValue(name, nodes[i].getAttribute(name))
1051+
)
1052+
continue outer;
1053+
}
1054+
return nodes[i];
10381055
}
10391056
return null;
10401057
}
@@ -1443,10 +1460,15 @@ function mountHeadResource(tag, props) {
14431460
headMountedResources.add(identity);
14441461
const url = props.href || props.src;
14451462
let el = null;
1446-
if (url != null) {
1447-
// Adopt a server-emitted element for the same resource. `rel` values are
1448-
// constrained to the resource set, so embedding in a selector is safe.
1449-
if (tag === "link") el = findAssetElement(`link[rel="${props.rel}"]`, "href", url);
1463+
// Adopt a server-emitted element for the same resource. `rel` values are
1464+
// constrained to the resource set, so embedding in a selector is safe.
1465+
// A responsive image preload legitimately has no href — the source set is
1466+
// the request — so it matches on a null href plus the identity qualifiers,
1467+
// the same rule the frame client applies.
1468+
if (tag === "link" && url == null && typeof props.imagesrcset === "string")
1469+
el = findAssetElement(`link[rel="${props.rel}"]`, "href", null, props);
1470+
else if (url != null) {
1471+
if (tag === "link") el = findAssetElement(`link[rel="${props.rel}"]`, "href", url, props);
14501472
else if (tag === "script") el = findAssetElement("script[src]", "src", url);
14511473
else el = findAssetElement("style[href]", "href", url);
14521474
}

‎packages/web/src/head.ts‎

Lines changed: 57 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,14 @@ export const RESOURCE_LINK_RELS = new Set([
3333
// changes cacheability. URL alone is not the identity. Integrity, referrer
3434
// policy, and fetch priority are deliberately first-registration metadata:
3535
// conflicting declarations do not create another resource identity.
36-
const RESOURCE_QUALIFIERS = ["as", "crossorigin", "type", "media", "imagesrcset", "imagesizes"];
36+
export const RESOURCE_QUALIFIERS = [
37+
"as",
38+
"crossorigin",
39+
"type",
40+
"media",
41+
"imagesrcset",
42+
"imagesizes"
43+
];
3744

3845
// Stylesheet attributes that are pure fetch metadata: they change how the
3946
// sheet is fetched, not whether it applies. A stylesheet whose extra
@@ -80,13 +87,58 @@ export function classifyHeadTag(desc) {
8087
return { resource: false };
8188
}
8289

83-
// Identity for a resource-class tag (evaluated props).
90+
// Canonical comparison value for one qualifier, or `null` when the attribute
91+
// is not part of the request. Two rules the raw prop value does not express:
92+
//
93+
// - `false` is ABSENCE, not a value. Both attribute writers drop it, so
94+
// `crossorigin={cond && "anonymous"}` must not fork an identity whose
95+
// markup is byte-identical to the unqualified one.
96+
// - `crossorigin` is a CORS settings attribute: three states, not a string
97+
// range. Absent is No CORS; `use-credentials` (ASCII case-insensitive) is
98+
// Use Credentials; every OTHER present value — `""`, a bare attribute, an
99+
// invalid value — is Anonymous. `crossorigin=""` and `crossorigin="anonymous"`
100+
// are one request and must be one identity, or the same font ships twice
101+
// and the client mounts a second link instead of adopting the server's.
102+
// - `as` is an enumerated attribute, ASCII case-insensitive: registration
103+
// lowercases it before emitting, so identity and adoption must fold the
104+
// same way or a client `as="IMAGE"` never adopts the server's `as="image"`.
105+
// - the responsive pair is filtered at registration: `""` and any
106+
// non-string value never reach the markup, so they must read as absent
107+
// here too, or a client `imagesrcset: ""` mounts a second link beside a
108+
// server link that (correctly) carries none.
109+
// The standalone frame client mirrors this function; keep them in step.
110+
export function qualifierValue(name, value) {
111+
if (value == null || value === false) return null;
112+
if (name === "imagesrcset" || name === "imagesizes")
113+
return typeof value === "string" && value !== "" ? value : null;
114+
const v = value === true ? "" : String(value);
115+
if (name === "as") return asciiLowerCase(v);
116+
if (name !== "crossorigin") return v;
117+
return v.length === 15 && v.toLowerCase() === "use-credentials" ? v.toLowerCase() : "anonymous";
118+
}
119+
120+
// HTML compares rel/as ASCII case-insensitively; toLowerCase would fold a
121+
// non-ASCII character onto an ASCII one the parser never matches.
122+
export function asciiLowerCase(value) {
123+
return value.replace(/[A-Z]/g, c => String.fromCharCode(c.charCodeAt(0) + 32));
124+
}
125+
126+
// Identity for a resource-class tag (evaluated props). Qualifier values are
127+
// length-prefixed: plain `:q=value` concatenation let a value containing the
128+
// delimiters forge another qualifier (`type: "a:media=b"` collided with
129+
// `type: "a", media: "b"`), which silently dropped the second resource. The
130+
// responsive attributes made that reachable — a source set is a long free-form
131+
// string that routinely carries `:` and `=`. The URL is length-prefixed for the
132+
// same reason: it is free-form too, and `/loader:type=6:module` with no `type`
133+
// otherwise reads as `/loader` with `type: "module"`. `tag` and `rel` come
134+
// from closed sets and cannot carry the delimiters.
84135
export function resourceIdentity(tag, props) {
85-
let id = "res:" + tag + ":" + (props.rel || "") + ":" + (props.href || props.src || "");
136+
const url = String(props.href || props.src || "");
137+
let id = "res:" + tag + ":" + (props.rel || "") + ":" + url.length + ":" + url;
86138
for (let i = 0; i < RESOURCE_QUALIFIERS.length; i++) {
87139
const q = RESOURCE_QUALIFIERS[i];
88-
const value = props[q];
89-
if (value != null) id += ":" + q + "=" + (value === true ? "" : value);
140+
const value = qualifierValue(q, props[q]);
141+
if (value !== null) id += ":" + q + "=" + value.length + ":" + value;
90142
}
91143
return id;
92144
}

‎packages/web/src/server-mock.ts‎

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,7 @@ function throwInBrowser(func: Function) {
88
console.error(err);
99
}
1010

11-
/** An explicit `<link rel="preload">` emitted by the SSR asset pipeline. */
12-
export type PreloadLink = {
13-
href: string;
14-
as: JSX.HTMLPreloadAs;
11+
type PreloadLinkAttributes = {
1512
type?: string;
1613
crossorigin?: JSX.HTMLCrossorigin;
1714
integrity?: string;
@@ -20,7 +17,50 @@ export type PreloadLink = {
2017
media?: string;
2118
};
2219

23-
/** Static asset manifest produced by a build (e.g. parsed Vite manifest.json). */
20+
/**
21+
* An explicit `<link rel="preload">` emitted by the SSR asset pipeline.
22+
*
23+
* `as` is the HTML Standard's set of preload destinations exactly — anything
24+
* else translates to null and the browser does nothing with the link.
25+
*
26+
* `imagesrcset` candidates must already be resolved by the integration: they
27+
* are carried verbatim (a relative candidate resolves against the DOCUMENT
28+
* URL, not the manifest base). Pair it with `imagesizes` whenever a candidate
29+
* uses a width descriptor, which the spec requires — without it the source
30+
* size falls back to `100vw` and the preload can miss the image the `<img>`
31+
* selects. Omitting `href` is the spec's own recommendation for the source-set
32+
* form: it would only serve browsers without `imagesrcset` support, and there
33+
* it would likely preload the wrong candidate.
34+
*/
35+
export type PreloadLink = PreloadLinkAttributes &
36+
(
37+
| {
38+
href: string;
39+
as: Exclude<JSX.HTMLPreloadAs, "image">;
40+
imagesrcset?: never;
41+
imagesizes?: never;
42+
}
43+
| {
44+
href: string;
45+
as: "image";
46+
imagesrcset?: string;
47+
imagesizes?: string;
48+
}
49+
| {
50+
href?: never;
51+
as: "image";
52+
imagesrcset: string;
53+
imagesizes?: string;
54+
}
55+
);
56+
57+
/**
58+
* Static asset graph consumed by the SSR pipeline. This is Solid's own
59+
* contract — a parsed Vite client manifest satisfies it structurally
60+
* (unknown fields pass through untyped), but any bundler integration can
61+
* produce it. Only these fields are ever read: `preloads` is Solid's
62+
* extension slot for explicit typed links the integration selects.
63+
*/
2464
export type AssetManifest = Record<
2565
string,
2666
{

0 commit comments

Comments
 (0)