Serve Responsive Images with srcset
Provide width descriptors and modern formats so devices download the smallest adequate image.
Task
Add srcset and sizes plus modern formats to deliver appropriately sized images.
When to use this
Mobile users download desktop-sized images, wasting bandwidth and slowing the largest contentful paint.
Prerequisites
- A build step to generate image variants
- An image component or markup
- Lighthouse to measure LCP
Steps
1. Generate variants and publish srcset with sizes.
<img
src="/img/hero-800.avif"
srcset="/img/hero-400.avif 400w, /img/hero-800.avif 800w, /img/hero-1600.avif 1600w"
sizes="(max-width: 600px) 100vw, 50vw"
width="1600" height="900" loading="eager" alt="Hero">Expected output: The browser chooses the smallest variant that fits the layout and density.
2. Verify the chosen variant and LCP.
npx lighthouse http://localhost:4321/ --only-audits=largest-contentful-paint --output=jsonExpected output: LCP improves and the network tab shows a smaller image on mobile.
Troubleshooting
Problem
Wrong image chosen
Solution
Make sizes match the CSS layout exactly; a wrong sizes causes oversized downloads.
Problem
Missing dimensions cause shift
Solution
Always set width and height so space is reserved.
Limitations
- Generating variants adds build cost.
- Modern formats need fallbacks.
- sizes must track layout changes.
What this recipe does
Add srcset and sizes plus modern formats to deliver appropriately sized images.
Mobile users download desktop-sized images, wasting bandwidth and slowing the largest contentful paint.
Prerequisites
- A build step to generate image variants
- An image component or markup
- Lighthouse to measure LCP
Procedure
- Generate variants and publish srcset with sizes.
<img
src="/img/hero-800.avif"
srcset="/img/hero-400.avif 400w, /img/hero-800.avif 800w, /img/hero-1600.avif 1600w"
sizes="(max-width: 600px) 100vw, 50vw"
width="1600" height="900" loading="eager" alt="Hero">
Expected result: The browser chooses the smallest variant that fits the layout and density.
- Verify the chosen variant and LCP.
npx lighthouse http://localhost:4321/ --only-audits=largest-contentful-paint --output=json
Expected result: LCP improves and the network tab shows a smaller image on mobile.
How to confirm it worked
Run the commands above and confirm every expected result in order. If a step does not produce the stated output, use the troubleshooting notes before continuing. A passing run shows the selected image matches the viewport, LCP improves, and no layout shift occurs on load.
Troubleshooting
Wrong image chosen — Make sizes match the CSS layout exactly; a wrong sizes causes oversized downloads.
Missing dimensions cause shift — Always set width and height so space is reserved.
Limitations
- Generating variants adds build cost.
- Modern formats need fallbacks.
- sizes must track layout changes.