Skip to content

Commit 5b34ece

Browse files
committed
RSCImage: default lazy images to sizes="auto" for optimal srcset selection
Apply sizes="auto, 100vw" to both the <source> elements and the <img> when no explicit sizes is provided and the image is lazy (non-priority). Per the HTML spec a <source sizes="auto"> only engages when its sibling <img> also "allows auto-sizes" (loading="lazy" + sizes starting with "auto"), so it must be set on the <img> too. Lets the browser pick the best candidate from the rendered width; degrades to 100vw on browsers without auto support. Verified in Chrome.
1 parent 596e989 commit 5b34ece

1 file changed

Lines changed: 18 additions & 2 deletions

File tree

src/RSCImage/index.tsx

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,23 @@ export function RSCImage({
5757
srcSetCandidates = [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4],
5858
referrerPolicy = 'no-referrer-when-downgrade',
5959
}: RSCImagePropTypes) {
60-
const webpSource = buildWebpSource(data, sizes);
61-
const regularSource = buildRegularSource(data, sizes, srcSetCandidates);
60+
// When no explicit `sizes` is given, default lazy images to `sizes="auto"`
61+
// so the browser picks the optimal `srcset` candidate from the rendered
62+
// width. Per the HTML spec, `auto` only engages when the `<img>` itself
63+
// "allows auto-sizes" (loading="lazy" AND a `sizes` starting with `auto`),
64+
// and a `<source>`'s `auto` only takes effect when its sibling `<img>` does
65+
// too — so `resolvedSizes` is applied to both the sources and the `<img>`
66+
// below. Skipped for `priority` (eager) images, where `auto` is invalid; the
67+
// `, 100vw` fallback preserves prior behavior on unsupporting browsers.
68+
const resolvedSizes =
69+
sizes ?? data.sizes ?? (priority ? undefined : 'auto, 100vw');
70+
71+
const webpSource = buildWebpSource(data, resolvedSizes);
72+
const regularSource = buildRegularSource(
73+
data,
74+
resolvedSizes,
75+
srcSetCandidates,
76+
);
6277

6378
const placeholderStyle: React.CSSProperties | undefined =
6479
usePlaceholder && data.base64
@@ -99,6 +114,7 @@ export function RSCImage({
99114
src={data.src}
100115
alt={data.alt ?? ''}
101116
title={data.title ?? undefined}
117+
sizes={resolvedSizes}
102118
{...loadingBehaviourProps}
103119
className={imgClassName}
104120
style={{

0 commit comments

Comments
 (0)