Project: an image pipeline
Build a pipeline for a store's photos: every width and format at a measured quality, picture markup that matches the layout, year-long caching, and measurement.
- 01Make every size and format a layout needsPick each format's quality with a visual score, make every width each slot needs, name each file by its content, and list them in a manifest.
- 02Write the markup from the manifestTurn a short tag into a picture element whose sizes copies the CSS, with width and height, and fetchpriority or lazy loading where they belong.
- 03Cache the files, and measure the resultKeep content-named files for a year, check pages with an ETag, and measure which file each screen took, the bytes and the LCP.
Four big photos for every screen
Meera, the designer, has made Leaf and Kettle a new home page. At the top is a big photo of this week's tea, mint tea. Under it are three popular teas, each with a photo. Meera sent her photos at full size, 1,200 or 1,600 pixels wide. Ravi copied them into the store as they were.
Asha opens the page on her phone, on the bus. The words come first. The big photo comes last, about three seconds after she tapped. Ravi's laptop gets the same four files. So does every other screen.
Her phone shows the big photo 350 CSS pixels wide. Why send it 1,600? And how do you give every screen the right file, without saving 93 files by hand?
Here is where this project ends. These are the home page's numbers in the lab, on four screens, before and after:
// Meera's home page in the lab: kB the store sent, and the LCP in ms.// The middle of 5 loads on each screen.const before = { phone1x: [348.6, 3100], phone3x: [348.6, 3080], laptop1x: [348.6, 716], laptop2x: [348.6, 724] };const after = { phone1x: [17.4, 1248], phone3x: [38.3, 1292], laptop1x: [20.3, 400], laptop2x: [60.8, 412] }; for (const screen of Object.keys(before)) { const [[kB, lcp], [newKB, newLcp]] = [before[screen], after[screen]]; console.log(`${screen}: ${kB} kB, LCP ${lcp} ms → ${newKB} kB, LCP ${newLcp} ms`);}- Lines 1 and 2 are comments. A kB is 1,000 bytes. LCP is when the largest thing on the screen appeared, here the big photo, in milliseconds (ms) from the tap.
- Line 3 holds two phones and two laptops before the project: the kB the store sent for the page, then the LCP. 1x and 3x are pixel ratios: how many dots a screen packs across one CSS pixel.
- Line 4 holds the same screens after the project.
- Lines 6 to 9 print one line per screen. The second is
phone3x: 348.6 kB, LCP 3080 ms → 38.3 kB, LCP 1292 ms.
Every screen now gets less than a fifth of the bytes. On the phones, the photo arrives about 1.8 seconds sooner. Why it matters: Google calls an LCP of 2.5 seconds or less good. Both phones went from over that line to well under it.
Here is Asha's phone, before and after. These are real frames, at the same moments:
Before, at 1,400 ms, only a thin strip of each photo is drawn. After, the big photo is already whole. The project gets there with a pipeline: a few scripts that turn Meera's originals into every file the page needs.
You hand a photo shop one photo. You have frames of four sizes at home. The shop prints the photo for each frame, on three kinds of paper, and stamps a code on the back of each print. In the envelope is a list of every print. At home, each frame gets the print that fills it.
- In real life: The one photo you hand in
- In an image pipeline: Meera's original, in originals/
- In real life: A print for each size of frame
- In an image pipeline: A file for each width a slot needs
- In real life: Glossy, matte or satin paper
- In an image pipeline: AVIF, WebP or JPEG
- In real life: The code on the back of each print
- In an image pipeline: The hash in each file's name
- In real life: The list in the envelope
- In an image pipeline: images.json, the manifest
Make every width and format a layout needs once, at a quality you measured. Name each file by its content. Then describe the layout in the markup, so each screen takes only the file it needs. Content-named files can be kept for a year. Then measure what each screen really took.
The project has four steps:
- Step 1: make every size and format, with a quality picked by a score.
- Step 2: write each photo's markup from the list of files.
- Step 3: send headers that keep the files for good, and check the pages.
- Step 4: measure which file each screen took, the bytes and the LCP.
Here is the whole pipeline, one script per row:
Build each step on your own copy. The store from lesson 45.5 now lives in a folder called site/, as in lesson 45.4's repository. Meera's photos are the course's tea photos, such as mint-tea.jpg. The course's files for each step are published. Save each home.html as index.html, then run node serve.mjs.
- Before (serve.mjs): Meera's home page, her photos and lesson 45.5's serve.mjs, moved next to site/.
- Step 1: sizes and formats (serve.mjs): images.config.mjs, pick-quality.mjs, build-images.mjs, and what they wrote: quality.json and images.json.
- Step 2: the markup (serve.mjs): write-markup.mjs, the page source in pages/, and the home page it wrote.
- Step 3: caching (serve.mjs): the new serve.mjs.
How the course recorded it
- The pipeline: the reader's own scripts, run with Node.js 22.23.3 on an Apple M1 Pro, 8 cores, 16 GB. They use sharp 0.34.3, with libvips 8.17.1, and SSIMULACRA2 from libjxl 0.12.0.
- The store: each version ran its own
serve.mjs, at a made-up address, https://shop.example. A small HTTPS server in front stood in for the network. Each answer waited 562.5 ms on the phones, like DevTools' Slow 4G, and 165 ms on the laptops, like Fast 4G. It sent the most urgent files first, as lesson 18.3's server did. - The screens: Chrome for Testing 157.0.8103.52. The phones were 390 by 844 pixels, at 1x and 3x, with the CPU 4× slower. The laptops were 1280 by 800, at 1x and 2x. Each version loaded 5 times on each screen, taking turns, after one round that wasn't kept.
- The numbers: each photo's file and bytes from the page itself, the LCP from Chrome's own entries, and what the store sent from the server's log. Then a new tab loaded the page again, for the repeat visit.
Step 1: make every size and format
First, Ravi moves Meera's photos into a folder called originals/. They stay there, untouched. Every file visitors get will be made from them.
Which widths does each slot need?
A slot is the space a photo fills on the page. Lesson 18.2 showed the rule: a screen needs the slot's width times its pixel ratio. The store has three slots. Ravi writes them in one file that every script reads:
export const SLOTS = { // The big photo on the home page: 350 px wide on a 390 px phone, 720 px on a computer. feature: { widths: [360, 720, 1080, 1440], sizes: "(max-width: 760px) calc(100vw - 40px), 720px" }, // The tea grid: two columns on a phone, 169 px each; three on a computer, 232 px each. thumb: { widths: [240, 360, 540], sizes: "(max-width: 599px) calc((100vw - 52px) / 2), (max-width: 760px) calc((100vw - 64px) / 3), 232px" }, // The photo on each tea's page: 350 px wide on a phone, 360 px on a computer. photo: { widths: [360, 720, 1080], sizes: "(max-width: 599px) calc(100vw - 40px), 360px" },};- Line 3 is the big photo, the
featureslot. It's 350 px wide on Asha's phone and 720 px on a laptop. So it gets 360 for a 1x phone, 720 for a laptop or a 2x phone, 1080 for a 3x phone and 1440 for a 2x laptop. - Line 5 is the tea grid, 169 or 232 px wide. Line 7 is the photo on each tea's own page.
- Each slot also has its
sizes. Step 2 uses it.
The same file lists which photos sit in which slots, and how to make each format:
export const FORMATS = { avif: { type: "image/avif", ext: "avif", encode: (image, quality) => image.avif({ quality }) }, webp: { type: "image/webp", ext: "webp", encode: (image, quality) => image.webp({ quality, effort: 6 }) }, jpeg: { type: "image/jpeg", ext: "jpg", encode: (image, quality) => image.jpeg({ quality, mozjpeg: true }) },}; // Every width a photo needs: the widths of all its slots, none wider than the original.export const widthsFor = (photo, originalWidth) => [...new Set(PHOTOS[photo].flatMap((slot) => SLOTS[slot].widths))].filter((width) => width <= originalWidth).sort((a, b) => a - b);- Lines 2 to 4 make AVIF, WebP and JPEG with sharp, a Node.js library that resizes and converts images. The settings are lesson 18.1's. Only the quality is left open.
- Lines 8 and 9 give every width a photo needs: all its slots' widths, none wider than the original. The mint tea photo sits in all three slots, so it gets six widths.
Pick each quality with a score
Each format's quality is a number from 1 to 100. Lower means fewer bytes and more damage. Lesson 18.1 showed how to choose it: make the file, then score it with SSIMULACRA2, a tool that rates how close a picture looks to the original. Its own help text calls 80 "very high quality": you can't tell it from the original side by side.
You play music at a party and want it as quiet as it can be. You turn it down, then ask the person in the back row. If they miss a word, you turn it up. You try halfway each time. The quietest volume the back row hears is the one you keep.
- In real life: The volume knob
- In an image pipeline: The quality setting
- In real life: The person in the back row
- In an image pipeline: The file that scores worst
- In real life: Hearing every word
- In an image pipeline: A score of 80 or more
- In real life: Trying halfway between too loud and too quiet
- In an image pipeline: The search in pick-quality.mjs
That's pick-quality.mjs. Its first part makes every file the pipeline will make, and scores the worst one:
// The lowest SSIMULACRA2 score of all the files, made in one format at one quality.async function worstScore(format, quality) { let worst = 100; for (const file of files) { const encoded = await FORMATS[format].encode(sharp(`originals/${file.photo}.jpg`).resize(file.width), quality).toBuffer(); await sharp(encoded).png().toFile(".quality/candidate.png"); const score = Number(execFileSync("ssimulacra2", [file.reference, ".quality/candidate.png"], { encoding: "utf8" })); worst = Math.min(worst, score); } return worst;}- Line 4 goes through every file: each photo, at each width it needs.
- Line 5 resizes the original and encodes it in one format, at one quality.
- Line 6 turns it back into a PNG, a lossless picture. Line 7 asks
ssimulacra2to compare it with the original at the same width. - Line 8 keeps the lowest score so far. Line 10 returns it.
Its second part searches for the lowest quality that passes:
// Halve the range each time, like guessing a number: too low, try higher; good enough, try lower.const quality = {};for (const format of Object.keys(FORMATS)) { let [low, high] = [50, 100]; while (low < high) { const middle = Math.floor((low + high) / 2); const worst = await worstScore(format, middle); console.log(`${format} at ${middle}: worst score ${worst.toFixed(1)}`); if (worst >= TARGET) high = middle; else low = middle + 1; } quality[format] = low;}- Line 4 starts with every quality from 50 to 100.
- Line 6 tries the middle one. Line 7 scores it.
- Line 9: if the worst file passed, the answer is this quality or lower, so the top of the range moves down to it. Line 10: if it failed, the answer is higher, so the bottom moves up past it.
- Line 12 keeps the answer when the range is down to one quality.
Here is what it printed for AVIF:
avif at 75: worst score 78.9
avif at 88: worst score 85.5
avif at 82: worst score 83.1
avif at 79: worst score 81.5
avif at 77: worst score 80.7
avif at 76: worst score 80.0Six tries found AVIF's quality, 76. WebP needed 91 and JPEG 87. The search took 124 seconds. Ravi runs it once, not on every build. Why it matters: one number per format, chosen by a score, beats a guess.
Which file scored worst? In every format, one of the biggest. Big files keep the most fine detail, like the grain on the table in Meera's photos, and fine detail is what a low quality smudges first. A quality that scores well on a small file can fail on a big one. That's why the script scores every width.
Make the files, and name each one by its content
const manifest = {};for (const photo of Object.keys(PHOTOS)) { const original = sharp(`originals/${photo}.jpg`); const { width, height } = await original.metadata(); const files = []; for (const w of widthsFor(photo, width)) { for (const [format, { ext, encode }] of Object.entries(FORMATS)) { const { data, info } = await encode(original.clone().resize(w), quality[format]).toBuffer({ resolveWithObject: true }); const hash = createHash("sha256").update(data).digest("hex").slice(0, 8); const file = `images/${photo}-${w}.${hash}.${ext}`; writeFileSync(`site/${file}`, data); files.push({ format, width: info.width, height: info.height, bytes: data.length, file }); } } manifest[photo] = { width, height, files };}- Line 2 goes through every photo. Line 4 reads its width and height.
- Lines 6 and 7 go through each width it needs, in each format.
- Line 8 resizes and encodes it at the picked quality.
- Line 9 makes a hash of the file's bytes: a short code that changes whenever one byte changes. It keeps the first 8 characters. Line 10 puts them in the name, like
mint-tea-1080.d8ad516b.avif. - Line 11 saves the file in
site/images/. Line 12 adds it to the list, with its width, height and bytes.
It made 93 files in 10.9 seconds, one at a time. The list is images.json, the manifest. Here is its start:
{ "mint-tea": { "width": 1600, "height": 1067, "files": [ { "format": "avif", "width": 240, "height": 160, "bytes": 1925, "file": "images/mint-tea-240.cd9bd08a.avif" }, { "format": "webp", "width": 240, "height": 160, "bytes": 2544, "file": "images/mint-tea-240.58ba34a4.webp" }, { "format": "jpeg", "width": 240, "height": 160, "bytes": 3269, "file": "images/mint-tea-240.e91e2731.jpg" }, …Line 6 is the mint tea photo's smallest AVIF: 1,925 bytes. That photo has 18 files in all. Here is every one of them:
Look at the three formats at the three biggest widths:
// The mint tea photo at three widths, in bytes: [AVIF, WebP, JPEG]. Every file scored 80 or more.const bytes = { 720: [5723, 11546, 14085], 1080: [16650, 35728, 31437], 1440: [39162, 73672, 60893] }; for (const [width, [avif, webp, jpeg]] of Object.entries(bytes)) { console.log(`${width} px: AVIF is ${Math.round((avif / jpeg) * 100)}% of the JPEG, WebP ${Math.round((webp / jpeg) * 100)}%`);}- Line 2 holds the mint tea photo's bytes in each format, at 720, 1080 and 1440 px.
- Line 5 prints each as a share of the JPEG. The first line is
720 px: AVIF is 41% of the JPEG, WebP 82%.
AVIF was always the smallest, under two thirds of the JPEG. WebP was not: at 1080 and 1440 px, it was bigger than the JPEG. Why it matters: measure on your own photos, because a format's name isn't a promise. And only a browser that can't show AVIF ever takes the WebP, because the browser takes the first type it can show.
Step 2: write the markup from the manifest
The files exist. Now each page must offer them, and the right markup is long. So Ravi doesn't write it by hand. In pages/, each page has a short tag for each photo:
<a class="feature" href="/mint-tea.html"> <img data-photo="mint-tea" data-slot="feature" class="feature-photo" alt="A glass of mint tea" fetchpriority="high"> <span>This week: Mint tea</span></a><!-- … and under Popular teas: --><img data-photo="green-tea" data-slot="thumb" class="thumb" alt="" loading="lazy">- Line 2 is the big photo.
data-photonames the original, anddata-slotnames the slot.altdescribes it.fetchpriority="high"says it's the LCP photo, the one to fetch first. - Line 6 is a popular tea.
loading="lazy"says it can wait until it's near the screen.
The script can't know what a photo shows, or which one is the LCP. Only the page's author knows that. Everything else comes from the manifest.
At a post office, you write a short note: who the parcel is for, and the town. A machine looks the rest up in its address book. It prints the full label, with the street, the postcode and a barcode. You never write those by hand, so they're never wrong.
- In real life: The short note you write: who and where
- In an image pipeline: The tag: data-photo, data-slot and alt
- In real life: The post office's address book
- In an image pipeline: images.json, the manifest
- In real life: The machine that prints the label
- In an image pipeline: write-markup.mjs
- In real life: The full label, barcode and all
- In an image pipeline: The <picture> element
function picture(line, indent, tag) { const photo = manifest[tag.match(/data-photo="([^"]+)"/)[1]]; const slot = SLOTS[tag.match(/data-slot="([^"]+)"/)[1]]; const filesIn = (format) => photo.files.filter((file) => file.format === format && slot.widths.includes(file.width)); const srcset = (format) => filesIn(format).map((file) => `/${file.file} ${file.width}w`).join(", "); const rest = tag.replace(/\s*data-(photo|slot)="[^"]*"/g, "").slice(4, -1).trim(); return [ `${indent}<picture>`, `${indent} <source type="${FORMATS.avif.type}" srcset="${srcset("avif")}" sizes="${slot.sizes}">`, `${indent} <source type="${FORMATS.webp.type}" srcset="${srcset("webp")}" sizes="${slot.sizes}">`, `${indent} <img ${rest} src="/${filesIn("jpeg")[1].file}" srcset="${srcset("jpeg")}" sizes="${slot.sizes}" width="${photo.width}" height="${photo.height}">`, `${indent}</picture>`, ].join("\n");}- Lines 2 and 3 look up the photo in the manifest and the slot in the config.
- Line 4 keeps the files of one format whose widths belong to this slot. Line 5 turns them into a
srcset: each file, then its width and aw. - Line 6 keeps the author's own attributes, without the two data ones.
- Lines 8 to 12 write a
<picture>. Lines 9 and 10 are a<source>for AVIF and one for WebP. The browser takes the first type it can show. - Line 11 is the
<img>, with the JPEGs. It keeps the author's attributes, and getswidthandheightfrom the original.
Here is the big photo's markup, as the script wrote it:
<picture> <source type="image/avif" srcset="/images/mint-tea-360.44b0d6c5.avif 360w, /images/mint-tea-720.3c3ee4d0.avif 720w, /images/mint-tea-1080.d8ad516b.avif 1080w, /images/mint-tea-1440.005db233.avif 1440w" sizes="(max-width: 760px) calc(100vw - 40px), 720px"> <source type="image/webp" srcset="/images/mint-tea-360.f637a27b.webp 360w, /images/mint-tea-720.3954e1ef.webp 720w, /images/mint-tea-1080.249dafa2.webp 1080w, /images/mint-tea-1440.dde1a63f.webp 1440w" sizes="(max-width: 760px) calc(100vw - 40px), 720px"> <img class="feature-photo" alt="A glass of mint tea" fetchpriority="high" src="/images/mint-tea-720.9180b2b8.jpg" srcset="/images/mint-tea-360.678764ba.jpg 360w, /images/mint-tea-720.9180b2b8.jpg 720w, /images/mint-tea-1080.f2f54cc1.jpg 1080w, /images/mint-tea-1440.7e62a4ae.jpg 1440w" sizes="(max-width: 760px) calc(100vw - 40px), 720px" width="1600" height="1067"></picture>- Line 2 offers the four AVIF widths. Line 3 offers the same in WebP.
- Line 4 is the
<img>that sits on the page. Itssrcsetoffers the same four widths as JPEGs, for a browser that can show neither AVIF nor WebP. Itssrcis only for a browser too old to readsrcset. widthandheightkeep the photo's shape before it arrives, so nothing jumps (lesson 18.3).
sizes copies the CSS
The browser picks a file as soon as it reads the tag, before the CSS arrives. So sizes tells it how wide the slot will be (lesson 18.2). Here is the CSS it copies:
* { box-sizing: border-box; }main { max-width: 760px; margin: 0 auto; padding: 8px 20px; }.feature { display: block; color: inherit; text-decoration: none; font-weight: 600; }.teas { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }@media (max-width: 599px) { .teas { grid-template-columns: repeat(2, 1fr); } .tea { grid-template-columns: 1fr; }}- Line 1 makes every width include the padding.
- Line 2 makes the page at most 760 px wide, with 20 px of padding on each side. So the big photo is the window minus 40 px, up to 720 px. That's its
sizes:(max-width: 760px) calc(100vw - 40px), 720px. - Line 4 puts the tea grid in three columns, with 12 px gaps: (720 − 24) / 3 = 232 px on a laptop.
- Line 6 makes it two columns on a window under 600 px: the window minus 40 px of padding and one 12 px gap, halved.
Does each sizes match the layout? The course measured each slot in Chrome at 13 window widths. Try Ravi's values, then change one and watch the rows:
The big photo- 320 px window280 px / 280 pxMatches the layout.
- 360 px window320 px / 320 pxMatches the layout.
- 390 px window350 px / 350 pxMatches the layout.
- 412 px window372 px / 372 pxMatches the layout.
- 480 px window440 px / 440 pxMatches the layout.
- 599 px window559 px / 559 pxMatches the layout.
- 600 px window560 px / 560 pxMatches the layout.
- 700 px window660 px / 660 pxMatches the layout.
- 760 px window720 px / 720 pxMatches the layout.
- 768 px window720 px / 720 pxMatches the layout.
- 1024 px window720 px / 720 pxMatches the layout.
- 1280 px window720 px / 720 pxMatches the layout.
- 1440 px window720 px / 720 pxMatches the layout.
For each window width, the slot your sizes gives, against how wide Chrome really drew the photo at that width. Too wide downloads more than the screen can show. Too narrow can look soft.
All three of Ravi's values match at every width. Try taking calc() away from the big photo's. Chrome skips a part it can't read, without a word, and uses the next one. Why it matters: a broken sizes gives no error. It only sends the wrong file.
Which file did each screen take?
Each screen multiplied the slot by its pixel ratio and took the first width at least that big. That's the HTML standard's rule, and Chrome 157.0.8103.52's code follows it. Notice that a bigger screen doesn't mean a bigger file. The 3x phone took a 1080 px photo; the 1x laptop, 720.
Read across each row of the table to see who decides each part of the picture:
| Part | Who decides | Where it comes from |
|---|---|---|
srcset | The pipeline. | images.json: every file it made for that slot, with its width. |
type on each <source> | The pipeline. | The format: AVIF first, then WebP. The <img> holds the JPEG. |
sizes | The layout. | images.config.mjs, which copies the widths in styles.css. |
width and height | The pipeline. | The original's size, so the page keeps the photo's shape before it arrives. |
alt | The page's author. | The tag in pages/, because only a person knows what the photo shows. |
fetchpriority and loading | The page's author. | The tag in pages/, because only the author knows which photo is the LCP and which ones can wait. |
Step 3: cache the files for good
A file in images/ is named after its own bytes. If Meera changes a photo, its files get new names. So a name never means two different files. That lets the server tell browsers to keep these files for a long time.
const PAGE = { "cache-control": "no-cache", "permissions-policy": "unload=()" };// A file in images/ is named by its content, so it never changes: keep it for a year, and never check it again.const LONG = { "cache-control": "public, max-age=31536000, immutable" };const headersFor = (path) => (path.startsWith("/images/") ? LONG : path.endsWith(".html") ? PAGE : { "cache-control": "no-cache" });- Line 1 is for pages:
no-cachemeans "check with the server before each use" (lesson 15.1). - Line 3 is for
images/.max-age=31536000keeps a file fresh for a year.immutablesays it will never change.publicsays any cache may keep it, even for a visitor who is logged in. - Line 4 picks the headers by the file's path. Styles and scripts are checked, like pages.
A library never changes a book on the shelf. A corrected book is a new edition, with a new number on its spine. So you can keep your copy for years. Before you read, you check the library's list of current editions. Most days, the librarian just says your list is still current.
- In real life: The edition number on the spine
- In HTTP caching: The hash in the file's name
- In real life: Keeping your copy for years
- In HTTP caching: max-age=31536000, immutable
- In real life: The library's list of current editions
- In HTTP caching: The page, checked on every visit
- In real life: "Your list is still current"
- In HTTP caching: A 304 Not Modified
The other change gives every response an ETag, so a check can be cheap:
// The ETag names this version of the file. If the browser already has it, a 304 answers with no body.const etag = `"${createHash("sha256").update(body).digest("hex").slice(0, 16)}"`;const headers = { "content-type": TYPES[extname(path)] ?? "application/octet-stream", etag, ...headersFor(path) };if (request.headers["if-none-match"] === etag) return response.writeHead(304, headers).end();response.writeHead(200, { ...headers, "content-length": body.length }).end(body);- Line 2 makes an ETag: a short code for this version of the file, from its hash.
- Line 3 adds it to the headers.
- Line 4 answers
304 Not Modified, with no body, if the browser sent back the same ETag inIf-None-Match. - Line 5 sends the whole file otherwise.
The headers, as a CDN gets them
A CDN is a set of servers that keep copies close to visitors (lesson 15.4). It asks serve.mjs the way the course did here, directly:
GET /images/mint-tea-1080.d8ad516b.avif HTTP/1.1 200 OKcontent-type: image/avifetag: "d8ad516b7bdad2e0"cache-control: public, max-age=31536000, immutablecontent-length: 16650- Line 1 is the request. Line 3 is the answer's status: the file came back whole.
- Line 4 says it's an AVIF. Line 5 is its ETag. Its first 8 characters match the name, because both come from the same hash.
- Line 6 lets every cache keep it for a year, unchecked.
There's no Vary: Accept. In lesson 18.4, one address could send AVIF or JPEG, so caches had to keep one copy per format. Here, each format has its own address, and the HTML picks. One address always means one file. Why it matters: a CDN can keep it under its address alone, with nothing to mix up.
You can also let an image CDN make the files. Cloudflare's docs give its address form, and an option, format=auto, that "serves the most efficient format that the requesting browser supports". For the store's photo, it would look like this:
https://<ZONE>/cdn-cgi/image/<OPTIONS>/<SOURCE-IMAGE>
https://shop.example/cdn-cgi/image/width=720,format=auto/originals/mint-tea.jpgLine 1 is the form from the docs. Line 2 asks for the original resized to 720 px, in the best format the browser takes. That address sends different formats to different browsers, so its caching works like lesson 18.4's.
The repeat visit
The course loaded the page again in a new tab, with the same browser:
// The repeat visit on the phone at 3x: how the store answered, and the bytes it sent.const before = { answers: ["/ 200", "/styles.css 200", "/analytics.js 200", "/app.js 200"], sent: 5063 };const after = { answers: ["/ 304", "/styles.css 304", "/analytics.js 304", "/app.js 304"], sent: 0 }; console.log(`Before: ${before.sent} bytes. After: ${after.sent} bytes.`);- Line 2 is before the project. The page, the styles and both scripts came back whole, with status 200.
- Line 3 is after step 3. Each came back as a
304. - Line 5 prints
Before: 5063 bytes. After: 0 bytes.
The photos aren't in either list. Chrome had them, so it never asked. That was already true before: lesson 45.5's server kept photos for a year. But they had names that never change. When Meera replaced a photo, returning visitors would keep the old one for up to a year. Lesson 15.1 showed exactly that with a stylesheet. Now a new photo gets a new name, and the page, checked every visit, names it.
Chrome doesn't use immutable. On a reload, it doesn't check files like these anyway (lesson 15.1). Firefox and Safari do use it:
Step 4: measure bytes and LCP
The markup offers many files. Which did each screen take? Ask the page. Every <img> knows the file it shows, in currentSrc. Resource Timing knows that file's bytes:
// Paste into the console of the store's home page.
for (const img of document.images) {
const entry = performance.getEntriesByName(img.currentSrc)[0];
console.log(img.currentSrc.split("/").pop(), entry.encodedBodySize, "bytes");
}- Line 2 goes through every image on the page.
- Line 3 finds the image's Resource Timing entry by its address.
encodedBodySizeis the file's size as it came over the network. - Line 4 prints the file's name and its bytes.
A delivery firm doesn't guess what each house got. The driver logs it: which parcel went to which house, how heavy it was, and when it arrived. If a house got the wrong parcel, the log shows it.
- In real life: Each house on the round
- In measuring: Each screen the course tested
- In real life: Which parcel went to which house
- In measuring: currentSrc: the file each photo came from
- In real life: The weight on each label
- In measuring: encodedBodySize: the file's bytes
- In real life: When the parcel arrived
- In measuring: The LCP
The course ran the same check on all four screens. Pick one:
Phone, 3xBefore
- mint-tea.jpg102,809 BThe big photo. 1,600 px wide, shown 350 px wide.
- green-tea.jpg91,879 BA popular tea. 1,600 px wide, shown 169 px wide.
- chamomile.jpg55,905 BA popular tea. 1,200 px wide, shown 169 px wide.
- oolong.jpg92,934 BA popular tea. 1,600 px wide, shown 169 px wide.
Page: 348,590 B. LCP: 3,080 ms.
After the project
- mint-tea-1080.avif16,650 BThe big photo. 349 px wide, shown 350 px wide.
- green-tea-540.avif4,119 BA popular tea. 169 px wide, shown 169 px wide.
- chamomile-540.avif5,026 BA popular tea. 169 px wide, shown 169 px wide.
- oolong-540.avif4,094 BA popular tea. 169 px wide, shown 169 px wide.
Page: 38,327 B. LCP: 1,292 ms.
Each row is one photo on the home page: the file Chrome took and its bytes, before the project and after it. Page is everything the store sent; LCP is when the big photo was on screen.
Every screen took the right size, every time. And look at what the store sent for the page: 348.6 kB before, and 17.4 to 60.8 kB after. The 2x laptop got the most, because it needs the most pixels.
Why the photo came sooner
Fewer bytes is only half of it. Here is the big photo's request on Asha's phone:
// The big photo on the phone at 3x: when its request left and its last byte came, in ms.const before = { left: 587.9, done: 3070.4, bytes: 102809 };const after = { left: 604.1, done: 1276.1, bytes: 16650 }; for (const [name, photo] of Object.entries({ before, after })) { console.log(`${name}: ${photo.bytes} bytes in ${Math.round(photo.done - photo.left)} ms`);}- Lines 2 and 3 hold when the request left, when its last byte came, and its bytes, before and after. The times come from Resource Timing.
- Lines 5 to 7 print how long each took:
before: 102809 bytes in 2483 msandafter: 16650 bytes in 672 ms.
The request left at about the same moment both times, as soon as the HTML named it. Before, all four photos left together, at the same urgency, and shared Asha's slow line. After, the big photo was the most urgent photo, and the popular teas didn't ask until 1,239 ms, after the page was laid out. Lazy loading didn't skip them: on every screen, they start inside the first screen. It only made them wait for the layout (lesson 18.3), and that moved them out of the big photo's way.
Most of the 672 ms left is the wait for an answer: 562.5 ms on this network. Why it matters: once the bytes are small, the wait is mostly the network's, not the file's. Lesson 17.2 splits LCP into parts to show which one to fix next, and lesson 17.3 shows how to start the photo early.
Keep it that way
Lesson 45.4's size check fails any file without a budget. A budget is a size limit with a reason. With content-named files, every new photo is a new name. So the pipeline gives each image a budget that keeps its key when the photo changes:
for (const [photo, { files }] of Object.entries(manifest)) { for (const file of files) { const key = `${photo} ${file.width} ${file.format}`; const gzip = gzipSync(readFileSync(`site/${file.file}`)).length; budgets.images[key] ??= Math.ceil((gzip * 1.1) / 100) * 100; budgets.files[file.file] = { gzip: budgets.images[key], why: `${key}: the first build's size plus a tenth. A new version of the photo keeps it.` }; }}- Line 1 goes through every photo in the manifest. Line 2 goes through its files.
- Line 3 makes a key from the photo, the width and the format, like
mint-tea 1080 avif. A new version of the photo has the same key. - Line 5 sets the key's budget once: today's gzip size plus a tenth, rounded up to the next 100 bytes. That's lesson 45.4's rule for bytes.
- Line 6 gives that budget to the file's current name, where check-size.mjs looks for it.
File gzip Brotli Budget
images/mint-tea-1080.249dafa2.webp 35,761 35,732 39,400 ok
images/mint-tea-1080.d8ad516b.avif 16,650 16,595 18,400 ok
images/mint-tea-1080.f2f54cc1.jpg 30,828 30,556 34,000 ok
…
106 files: all within budget.Line 1 is the header. Lines 2 to 4 are the mint tea photo's three 1080 px files, each under its budget. The last line says every file passed, images and the rest of the store. Why it matters: if Meera's next mint tea photo makes a file more than a tenth bigger, the pull request fails, before any visitor downloads it.
Which step fixes this photo?
Each card is a problem with a store's photos. Sort it by the step of this project that fixes it:
- Each photo exists in one size only, 1,600 px wide
- No photo has an AVIF version
- The laptop takes a file for its whole window, not for the 232 px grid
- The big photo waits behind three small ones
- Returning visitors see last month's photo after Meera replaced it
- Every repeat visit downloads the whole page again
- You don't know if the 3x phone got a sharp enough file
Sort each problem by the step that fixes it.
Common mix-ups
- "One quality is right for every width." No. At AVIF 76, the mint tea photo scored 89.3 at 240 px and 80.0 at 1440 px. Score every file you make.
- "WebP is always smaller than JPEG." No. With both scoring 80 or more, the mint tea photo's WebP was bigger at 1080 and 1440 px.
- "A bigger screen needs a bigger file." No. The 3x phone took a 1080 px file, and the 1x laptop a 720 px one. The slot and the pixel ratio decide.
- "If sizes has a mistake, the browser says so." No. Chrome skips a part it can't read and uses the next one, with no error.
- "loading=lazy saves bytes on every page." No. On this short page, the lazy photos still loaded. They just waited until after the big photo.
- "Without immutable, Chrome checks every cached file on a reload." No. Chrome skips that check for files like these anyway. immutable helps in Firefox and Safari.
Practice exercises
Answer first, then use the hints. Two use the playgrounds, one uses DevTools on a published page, and one uses Cloudflare's docs.
Which width of a popular tea's photo does a phone 390 px wide, at pixel ratio 2, take? What does the last line print?
// Which thumbnail does a phone 390 px wide, at pixel ratio 2, take?
const widths = [240, 360, 540];
const slot = (390 - 52) / 2;
const needed = slot * 2;
console.log(widths.find((width) => width >= needed));360. A 2x phone needs 338 pixels across each tea's photo, and 360 is the first width that covers it.
The big photo on the phone at 3x, before and after. What does the last line print?
// The big photo on the phone at 3x, in bytes: Meera's file, then the pipeline's.
const before = 102809;
const after = 16650;
console.log(`${Math.round((1 - after / before) * 100)}% smaller`);84% smaller. The 1080 px AVIF has fewer pixels than Meera's 1600 px file, in a smaller format.
After the project, how many bytes was the chamomile photo on the phone at 1x?
2,249 bytes: the 240 px AVIF. Before the project, the same phone downloaded Meera's 55,905-byte file.
For the tea grid, type 50vw as the sizes. At a 599 px window, how many px too wide is it?
26 px too wide. 50vw forgets the padding and the gap: (599 - 52) / 2 is 273.5, not 299.5.
Open the store after step 3 in a window 600 px wide at pixel ratio 2. Which width of the big photo does Chrome take?
mint-tea-1440.005db233.avif. The slot is 600 - 40 = 560 px, times 2 is 1,120, and 1440 is the first width that covers it.
Read Cloudflare's image optimization features. What quality does it use when you don't set one?
85. A CDN's default is one number for every photo. pick-quality.mjs measures yours instead.
Check your understanding
For each question, ask which step it's about: the files, the markup, the caching or the measuring.
Question 1 of 7Why does pick-quality.mjs score every file it will make, not one width of one photo?
Choose an answer to see the explanation.
Question 2 of 7Chrome took a bigger file for the big photo on the phone at 3x than on the laptop at 1x. Why?
Choose an answer to see the explanation.
Question 3 of 7The store sends AVIF to Chrome and JPEG to older browsers. Why doesn't serve.mjs need a Vary: Accept header?
Choose an answer to see the explanation.
Question 4 of 7Why is it safe to keep a file in images/ for a year without checking it?
Choose an answer to see the explanation.
Question 5 of 7On the repeat visit after step 3, the page, styles and scripts came back with no body. What did the ETag do?
Choose an answer to see the explanation.
Question 6 of 7Before the project, why did the big photo arrive so late on the phones?
Choose an answer to see the explanation.
Question 7 of 7What does this sizes function print?
Read the code, then predictconst slot = (vw) => (vw <= 599 ? (vw - 52) / 2 : vw <= 760 ? (vw - 64) / 3 : 232); console.log(slot(390), slot(700), slot(1280));Choose an answer to see the explanation.
Key takeaways
- Write down each slot's widths once, from the layout, at every pixel ratio you serve.
- Pick each format's quality with a score, over every file you make. The biggest files score worst.
- Name each file by a hash of its bytes, and list every file in a manifest.
- Write the picture markup from the manifest. Let the author say what the photo shows, which is the LCP, and which can wait.
- Keep content-named files for a year, check pages with an ETag, and measure which file each screen really took.
Remember the one-liner.
Make every size once, name it by its content, describe the layout in the markup, cache it for good, and measure what each screen took.
Sources
The facts on this page come from these docs, standards and source files:
- Largest Contentful Paint (LCP), web.dev.
- Output options: avif, webp and jpeg, sharp.
- Resizing images: resize, sharp.
- SSIMULACRA 2: what each score means, Cloudinary on GitHub.
- HTML Standard: the picture element, WHATWG.
- HTML Standard: parse a sizes attribute, WHATWG.
- HTML Standard: select an image source, WHATWG.
- html_srcset_parser.cc, lines 379 to 412: how Chrome picks a file from srcset, Chromium source.
- Using responsive images in HTML, MDN.
- <img>: The Image Embed element, MDN.
- RFC 9218: Extensible Prioritization Scheme for HTTP, the IETF.
- RFC 9111: HTTP Caching, the IETF.
- RFC 8246: HTTP Immutable Responses, the IETF.
- RFC 9110: HTTP Semantics, ETag and 304 Not Modified, the IETF.
- Cache-Control header, MDN.
- Images: optimization features, Cloudflare.
- Resource Timing: transferSize and encodedBodySize, W3C.
- HTMLImageElement: currentSrc property, MDN.
Step 4's script is published too: image-budgets.mjs.
Coming next: Capstone: audit a real site. You'll choose a public site, read its field data, and prove two fixes with experiments.