
Image Optimization: srcset, AVIF, and the Sizes Attribute
One photo from this blog we picked for the experiment, 1600 wide, 366 kB, and on the Mac with sips we cut from it a 400 and an 800 copy, because we wanted to catch Chrome in the act, which file does he pull when we write the img in this way or that way.
Box on the page 400 px, our screen is retina with density 2. We write srcset with three files and, like many people, no sizes. He pulls the 1600! For a 400 box! We were looking on it and then remembered, when he chooses the file the CSS is not yet his business, without sizes he takes that the picture is full window wide, and the window was 1739. Add sizes="400px", refresh, now 800 comes, 149 kB, on screen you see no difference at all. With loading lazy plus sizes auto, also 800.
<img
src="/img/team-800.jpg"
srcset="/img/team-400.jpg 400w,
/img/team-800.jpg 800w,
/img/team-1600.jpg 1600w"
sizes="(min-width: 1024px) 600px, 100vw"
width="1600"
height="900"
alt="The support team at their desks">
After this we played with formats and one belief of ours broke. All three at 800 px: JPEG 149 kB, AVIF q60 67 kB, WebP q75 from cwebp 66 kB. Wait, WebP won? On this photo, with these numbers, by 1 kB, and q60 in one tool is not q60 in another, so don't quote us, test your own. In picture element the AVIF source was taken by Chrome immediately.
<picture>
<source
type="image/avif"
srcset="/img/team-400.avif 400w, /img/team-800.avif 800w"
sizes="(min-width: 1024px) 600px, 100vw">
<img src="/img/team-800.jpg" width="1600" height="900"
alt="The support team at their desks">
</picture>
import sharp from 'sharp';
const widths = [400, 800, 1600];
for (const width of widths) {
const image = sharp('src/team.jpg').resize({ width, withoutEnlargement: true });
await image.clone().avif({ quality: 50 }).toFile(`public/img/team-${width}.avif`);
await image.clone()
.jpeg({ quality: 75, mozjpeg: true })
.toFile(`public/img/team-${width}.jpg`);
}
Oh, and our fail of the day, resaving big JPEG with quality 75 to make it lighter produced 411 kB, heavier than the original, delete.
See also: our responsive design post and web performance basics.