Web browsers can be smart about images. Given a set of variants at different sizes, each tagged with which display density it is meant for, the browser looks at the display, picks exactly one file, and downloads only that one. The others are never fetched over the network. This demo shows the choice happening live.
The <picture> element below carries three variants tagged with density descriptors. The browser reads what it knows about the display, matches a variant, and downloads only that one file. The other two are skipped entirely - never fetched over the network.
window.devicePixelRatio
window.innerWidth
window.innerHeight
window.screen.width / .height
window.screen.colorDepth
navigator.userAgent - click the BROWSER INFO tab on the right for the full local report
The browser has no way to know what mars-2x.jpg means from the filename. The code tells it by writing a density descriptorspec ↗ after each URL in the srcset:
The filenames themselves are irrelevant. Naming them a.jpg, b.jpg, c.jpg would work identically - only the 1x / 2x / 3x labels matter.
The OS reports the physical pixel density to the browser via window.devicePixelRatio. Right now that value is ?.
It walks through the srcset, finds the URL labeled ?, and picks it - per the algorithm in HTML spec 4.8.4.2.1.
Only one HTTP request went out. The other two files were never fetched.
<img
src="https://periscoped-website-images.s3.us-east-1.amazonaws.com/demo/responsive-imaging/mars-1x.jpg"
srcset="
https://periscoped-website-images.s3.us-east-1.amazonaws.com/demo/responsive-imaging/mars-1x.jpg 1x,
https://periscoped-website-images.s3.us-east-1.amazonaws.com/demo/responsive-imaging/mars-2x.jpg 2x,
https://periscoped-website-images.s3.us-east-1.amazonaws.com/demo/responsive-imaging/mars-3x.jpg 3x
"
alt="Perseverance dust devil selfie"
width="800" height="476">
Three files listed with density descriptors. The browser handles the rest per the HTML Living Standard section 4.8.4.2.1.
All three variants displayed side-by-side using plain <img src> - no srcset. The browser only downloaded one of these in the picker above, but all three are shown here for comparison. The variant the browser selected is highlighted in green.
| File | Dimensions | Total pixels | File size | vs master |
|---|---|---|---|---|
| mars-original.jpg | 12,033 × 7,168 | 86.3 MP | 8.38 MB | - |
| mars-3x.jpg | 3,600 × 2,144 | 7.72 MP | 1.88 MB | 22% of master |
| mars-2x.jpg | 2,400 × 1,429 | 3.43 MP | 862 KB | 10% of master |
| mars-1x.jpg | 1,200 × 715 | 0.86 MP | 250 KB | 3% of master |