You cannot tune what you cannot measure, and a single number from your own machine is a poor measurement. Performance data comes in two kinds that answer different questions.
Lab data
Field data
Where it comes from
a script or tool loads the page in a controlled setup
real visitors' browsers report as they browse
Conditions
fixed device, network and cache state
every device, network and location your users have
Good for
finding causes, testing a fix before release, catching regressions in CI
knowing whether users are inside the target
Weak at
saying how real users fare
explaining why a number is bad
Lab data is repeatable, so a change in the number means a change in the page. Field data is honest, so it is the number the 75th percentile targets refer to. Teams use field data to decide where the problem is and lab data to fix it. Every timing in this chapter is lab data from this machine: Chrome 157 driven by a script, with the CPU slowed four times and the network limited to an assumed 1.6 Mbps and 150 ms round trip. Absolute numbers vary from run to run, so read the shape of each result, not the exact digits.
Chrome and other browsers expose what happened through the Performance Observer API. You ask for one kind of record, an entry type, and the browser calls you back with entries as they occur. The entries that matter most are listed below.
Entry type
What each entry reports
navigation
timings of the page load itself: first byte, DOM ready, load event
paint
first paint and first contentful paint
largest-contentful-paint
each new candidate for the largest element in view
resource
timings of each file the page fetched
event
how long input events took, from the user's action to the next frame
longtask
tasks that blocked the main thread for over 50 ms
layout-shift
each unexpected movement of visible content
What the browser records
The test page has a heading, a 235 KB image and a button whose click handler blocks the main thread for 250 ms. A small script starts one observer per entry type and collects every entry.
html
<script>
window.seen = []
const types = ['navigation', 'paint', 'largest-contentful-paint',
'resource', 'event', 'longtask', 'layout-shift']
for (const type of types) {
new PerformanceObserver((list) => {
for (const e of list.getEntries()) window.seen.push(e.toJSON())
}).observe({ type, buffered: true, durationThreshold: 40 })
}
document.querySelector('#add').addEventListener('click', () => {
const end = performance.now() + 250
while (performance.now() < end) {}
})
</script>
p1.html: one observer per entry type.
A Playwright script serves the page, throttles it, waits, clicks the button with a real mouse event and prints what the observers saw.
navigation first byte 152 ms | load event 1555 ms
paint first-paint 276 ms
paint first-contentful-paint 276 ms
lcp candidate: the heading text at 276 ms
lcp candidate: hero.png at 1560 ms
resource hero.png 1351 ms 235 KB
event click lasted 264 ms
longtask 256 ms
layout-shift entries: 0
Output (Chrome 157, lab, this machine, 4x CPU throttling)
The navigation entry says the first byte arrived at 152 ms, which is mostly the 150 ms of simulated round trip. The first paint is the heading text at 276 ms. LCP then produced two candidates: the heading, and later the image at about 1.56 s, which became the final LCP because it is the larger element. The image took 1,350 ms to download: 235 KB over a 200 KB/s link takes about 1.2 s, plus the round trip.
The click lasted 264 ms and the long task entry shows the 256 ms handler. No layout shift was recorded, so the layout-shift observer stayed silent. The image candidate arrives just after the load event at 1,555 ms. In four runs of this script it came at 1,560, 1,560, 1,568 and, once, 1,948 ms, and the first paint moved between 276 and 408 ms. That spread is one reason to repeat a lab run several times and keep the median.
Percentiles, and the web-vitals library
Field data arrives as thousands of values, and a single summary hides the slow visits. The script below uses 20 invented LCP samples to compare the mean with the 75th percentile, defined in the requirements chapter, and with the share of visits inside the 2,500 ms target.
js
// Why averages mislead: invented LCP samples, three summaries.const lcpMs = [900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700,
1800, 1900, 2000, 2100, 2200, 2800, 3000, 3200, 3500, 4000, 4500]
const mean = lcpMs.reduce((a, b) => a + b, 0) / lcpMs.length
const sorted = [...lcpMs].sort((a, b) => a - b)
const p75 = sorted[Math.ceil(0.75 * sorted.length) - 1]
const meet = lcpMs.filter((v) => v <= 2500).length
console.log('visits:', lcpMs.length)
console.log('mean LCP:', Math.round(mean), 'ms')
console.log('75th percentile:', p75, 'ms')
console.log(`visits within 2,500 ms: ${meet} of ${lcpMs.length}`)
p1b.mjs: invented samples, three summaries.
text
visits: 20
mean LCP: 2135 ms
75th percentile: 2800 ms
visits within 2,500 ms: 14 of 20
Output (Node 24)
The mean, 2,135 ms, looks like a pass. The 75th percentile is 2,800 ms, which fails, and only 14 of 20 visits, 70%, are inside the target when the target asks for 75%. A fifth of the visitors waited more than three seconds, and an average smooths that away. This is why web.dev recommends the 75th percentile, measured separately for mobile and desktop.
You rarely write the observers yourself. The web-vitals library from the requirements chapter wraps them and applies the rules for each metric. Its attribution build adds the element, resource or event behind a number, which is what you need to start a fix. A page sends those values to its own endpoint, usually with navigator.sendBeacon, and a dashboard computes percentiles over them. Where you cannot collect field data, run lab measurements in continuous integration with fixed conditions and watch for changes.
A team tunes LCP using only their own machines on office Wi-Fi. What is missing?
Field data, which shows real devices and networks.
The 75th percentile target refers to real visitors, so a lab run cannot say whether users are inside it.
In the run above the page produced two LCP candidates. Why is the image the final one?
LCP reports the largest element in view, and each larger element replaces the previous candidate.
The image is larger than the heading text, so it replaced it.
The mean LCP of a sample is 2,135 ms, but its 75th percentile is 2,800 ms. Does it meet a 2,500 ms target at the 75th percentile?
No. The 75th percentile is above 2,500 ms, so at least a quarter of visits are slower than the target.
The mean hides the slower tail.
Part 2 · Largest Contentful Paint
Four parts of a slow LCP
Largest Contentful Paint is the time from the start of navigation until the largest image or block of text in the first screen is painted. Most often it is a hero image or a large heading. The target is 2.5 seconds or less at the 75th percentile, and above 4 seconds is poor.
A single number does not say what to fix, so web.dev splits LCP into four parts that add up to it. When the LCP element is an image, they are as follows.
Part
It runs from
To
web.dev's rough share of a good LCP
Time to first byte (TTFB)
start of navigation
first byte of the page
about 40%
Resource load delay
first byte
the browser starts fetching the image
under 10%
Resource load duration
fetch starts
image fully downloaded
about 40%
Element render delay
image downloaded
image painted
under 10%
Time to first byte (TTFB)
It runs fromstart of navigation
Tofirst byte of the page
web.dev's rough share of a good LCPabout 40%
Resource load delay
It runs fromfirst byte
Tothe browser starts fetching the image
web.dev's rough share of a good LCPunder 10%
Resource load duration
It runs fromfetch starts
Toimage fully downloaded
web.dev's rough share of a good LCPabout 40%
Element render delay
It runs fromimage downloaded
Toimage painted
web.dev's rough share of a good LCPunder 10%
The shares are guidelines, not rules. They say where time should go: waiting for the server and downloading are unavoidable, while the delay before the browser starts the fetch and the delay before it paints are waste. If either "delay" part is large, the fix is about order and scheduling, not about making files smaller.
The script measures all four parts from the browser's own records: the navigation entry gives the first byte, the resource entry for the image gives its start and end, and the LCP entry gives the paint time.
The same 235 KB hero image is placed in the page in five ways. A render-blocking stylesheet takes 200 ms to arrive and a script takes 150 ms. For each variant the script runs five times and keeps the best run, because the paint time of a headless browser is noisy.
hero alone
variant TTFB delay load render LCP
script inserts img 1513041339101804
img in HTML 15143135291556
img + fetchpriority 151401365121568
script + preload 151441348171560
img loading=lazy 1513091341111812
with three thumbnails ahead
variant TTFB delay load render LCP
img in HTML 15139180772004
img + fetchpriority 151441812132020
Output (Chrome 157, lab, this machine, ms, best of five runs)
The variant where a script inserts the image, and the lazy variant, both have a resource load delay near 300 ms and an LCP near 1.8 s. The browser cannot start fetching an image it has not found, and a script-inserted image is found only after the script has downloaded and run. A lazy image is deferred until layout shows it is near the viewport, which costs about the same here. When the image is in the HTML, the browser's preload scanner finds it while the stylesheet is still downloading, so the delay falls to about 45 ms and LCP to about 1.55 s, 248 ms sooner.
A preload link in the head recovers the same time for the script-inserted image, because the browser now knows about the image from the first HTML bytes. web.dev recommends it when the image is referenced only from CSS or JavaScript. fetchpriority="high" made no difference here. It is a hint about which request matters most when several compete. The lower table adds three small thumbnails ahead of the hero, so the requests do compete, and the LCP is 2.0 s with or without the hint: the hero finished only after all four files had come over the same throttled link. This lab therefore cannot show a gain from the hint, and we do not claim one. Whether it helps depends on how the browser and the server order requests on a real connection, which a local HTTP/1.1 server under throttling does not reproduce. web.dev advises setting it on only one or two images, so that the hint keeps its meaning.
Two conclusions follow. First, the biggest wins in this run came from discovery: put the LCP image in the HTML as a plain img, never behind a script, and never mark it loading="lazy", which web.dev says directly. Second, once the file is discovered early, only fewer bytes make it faster, which is the subject of the images lesson.
A budget from a lab run
The scene turns the slowest variant into a budget. It adds the four parts of the run, compares the total with the target and shows what the fix buys.
Animated sceneAn LCP budget from a lab run0:16
Room left after the fix: ≈ 944 ms (lab run, assumed 1.6 Mbps link)
Read it as steps
The four parts of one throttled run, added up and compared with the 2.5 second target.
The load duration is more than 1.3 s of a 1.8 s total, so even the better page leaves little room if the image grows. The budget view makes that trade explicit: every extra 100 KB on this link costs about half a second of LCP. A real project would repeat the calculation with its own link assumption, and then set a byte limit on the hero image, as the requirements chapter did for a whole page.
Which two parts of LCP are mostly waste, and what kind of fix applies to them?
Resource load delay and element render delay.
They are about order and scheduling: find the image earlier and do not block painting it. Smaller files do not help them.
In the run, why did fetchpriority="high" change nothing?
With the hero alone nothing competes with it, so a priority hint has nothing to reorder.
With three thumbnails ahead the LCP was still the same with or without the hint, because the throttled link was shared and the hero finished last either way. This lab shows no gain, so do not promise one.
A product page uses loading="lazy" on every image, including the hero. What happens to LCP and why?
It gets later, by about 250 ms in the run, because the browser waits to decide the image is near the viewport before fetching it.
web.dev says never to lazy-load the LCP image.
Part 3 · Interaction to Next Paint
Three parts of an interaction
Interaction to Next Paint measures how quickly a page responds to input. For each click, tap or key press it takes the time from the action until the browser paints the next frame, and the page's INP is close to the worst of them. Scrolling, hovering and zooming are not counted. On pages with more than 50 interactions, one slowest interaction is ignored for every 50, so a single random hiccup does not decide the score. Good is 200 ms or less, and poor is above 500 ms.
web.dev splits each interaction into three parts. Input delay is the wait before any handler can start, usually because the main thread is busy with something else. Processing time is the time the handlers take. Presentation delay is the time from the end of the handlers to the next frame on screen. Event Timing, the browser API behind INP, reports the timestamps, so the script can take them apart.
js
const busy = (ms) => {
const end = performance.now() + ms
while (performance.now() < end) {}
}
const later = () => new Promise((r) => setTimeout(r))
const chunks = async (pause) => {
for (let i = 0; i < 6; i++) { busy(50); await pause() }
}
const worker = new Worker(URL.createObjectURL(new Blob([
`onmessage = () => {
const end = performance.now() + 300while (performance.now() < end) {}
postMessage('done')
}`])))
worker.onmessage = () => { out.textContent = 'Done' }
window.mode = 'sync'
go.addEventListener('click', async () => {
out.textContent = 'Working'// feedback firstif (mode === 'sync') busy(300)
if (mode === 'yield') await chunks(() => scheduler.yield())
if (mode === 'timeout') await chunks(later)
if (mode === 'worker') return worker.postMessage('go')
out.textContent = 'Done'
})
The script runs two cases. In the first the page is idle and the handler works for 300 ms. In the second the handler does nothing, but the click arrives at the start of a 400 ms task that the page is already running.
js
console.log('1. one interaction in three parts (ms)')
console.log('case'.padEnd(26) + 'input delay handler paint total')
const row = (label, m) => console.log(label.padEnd(26) +
num(m.input).padStart(11) + num(m.work).padStart(9) +
num(m.paint).padStart(7) + num(m.total).padStart(7))
let page = await open('sync') // handler: 300 msawait page.click('#go')
row('idle page, 300 ms handler', await measure(page))
page = await open('none') // handler does no workconst box = await page.locator('#go').boundingBox()
await page.evaluate(() => setTimeout(() => {
const end = performance.now() + 400while (performance.now() < end) {}
}, 0))
await page.mouse.click(box.x + 5, box.y + 5) // lands in the task
row('click during 400 ms task', await measure(page))
p3.mjs: the two cases.
text
1. one interaction in three parts (ms)
case input delay handler paint total
idle page, 300 ms handler 13002304
click during 400 ms task 40000400
Output (Chrome 157, lab, this machine, ms)
In the first case the handler is the whole cost: 300 of 304 ms. In the second case the handler is free, yet the interaction takes 400 ms, because it waited 400 ms for the busy thread. The user cannot tell the difference. They tapped and nothing happened. This is why INP is about the whole main thread, not only your click handler: any long task that is running when a tap arrives becomes input delay.
Event Timing rounds durations to the nearest 8 ms, so small differences in these figures are not meaningful. What is meaningful is the size: both cases are well past the 200 ms target.
Yielding and workers
A long task is a task that holds the main thread for over 50 ms. The cure is to cut slow work into pieces and let the browser run other work, including painting and input handlers, between them. Giving the thread back is called yielding. The page below does 300 ms of work in four ways: in one block, in six 50 ms chunks that yield with scheduler.yield(), in six chunks that yield with setTimeout, and in a Web Worker, which is a separate thread that cannot touch the page.
js
for (const mode of ['sync', 'yield', 'timeout', 'worker']) {
page = await open(mode)
await page.click('#go')
const m = await measure(page)
console.log(mode.padEnd(10) + num(m.total).padStart(19) +
num(m.gap).padStart(19))
}
p3.mjs: the four ways.
text
2. 300 ms of work, four ways (ms)
how click to next paint longest frame gap
sync 304291
yield 56100
timeout 5650
worker 169
Output (Chrome 157, lab, this machine, ms)
Without yielding, the user waits 304 ms for the first paint and the longest gap between frames is 291 ms, so the page is frozen. Both chunked versions show their first feedback in 56 ms, since the handler sets the text to "Working" and returns at the first yield. The Web Worker version needs just 16 ms and its longest frame gap is 9 ms, because the main thread did no heavy work at all.
The last column separates the two ways of yielding. With setTimeout the longest gap between frames was 50 ms, one chunk, in every run. With scheduler.yield() it was 100 ms in the run above, and across four runs of this script it was 100, 108, 150 and 542 ms. Three headed and three headless repeats of just those two modes gave the same split: 100 to 150 ms against 50 to 58 ms. So in this lab the scheduler.yield() version gave longer frame gaps than setTimeout, and the effect was not an artefact of headless mode. The cause is not established. MDN and web.dev say what yield is for: its continuation is prioritised, so it runs before other tasks of its priority that are already queued, while a setTimeout continuation goes to the back of the queue. That stops your own work being overtaken. Neither says it delays painting, so we do not claim a cause. Measure your own page before choosing. scheduler.yield() is also not in every browser: MDN marks it as not Baseline, and web.dev says to check for both scheduler and its yield method and to fall back to setTimeout. Moving work to a Worker avoids the problem when the work does not need the DOM.
The loop in motion
The scene replays the first and the third version of the handler in the browser's event loop, which runs one task at a time and paints between tasks when it can.
Animated sceneA tap behind a long task0:21
Watch for the tap waiting behind a 300 ms task
Read it as steps
A tap waits for a 300 ms task, then runs between 50 ms chunks.
In the first half the tap is queued behind the whole task and the page cannot paint until it finishes. In the second half the tap arrives during chunk 1. When chunk 1 yields, its continuation goes to the back of the queue behind the tap, so the tap runs next and the browser has a chance to paint before chunk 2. The scene shows the setTimeout version. The scene is a model of the loop, not a recording. With scheduler.yield() the continuation would be queued ahead of other tasks of its priority, which MDN describes as the front of the queue; the table above measured longer frame gaps for that version in this lab, cause not established.
A click handler does no work, but INP for that click is 400 ms. What is the most likely cause?
Input delay: the main thread was busy with a long task when the click arrived.
In the run, 400 of the 400 ms was input delay.
Why did the Web Worker version keep frames smooth while the chunked versions did not fully?
The heavy work ran on another thread, so the main thread stayed free to paint.
Chunked work still runs on the main thread between frames.
What should code check before calling scheduler.yield(), and what is the fallback?
Check that scheduler exists and has a yield method.
Fall back to a promise wrapped around setTimeout.
Part 4 · Cumulative Layout Shift
How a shift is scored
Cumulative Layout Shift measures how much visible content moves without the user asking for it. Everyone has tapped a button that moved a moment before the tap. The target is 0.1 or less at the 75th percentile, and above 0.25 is poor.
Each unexpected movement is a layout shift, and its score is the product of two fractions. The impact fraction is the area covered by the elements that moved, before and after, as a share of the viewport. The distance fraction is the largest distance any of those elements moved, as a share of the larger side of the viewport. For example, an impact fraction of 0.5 and a distance fraction of 0.3 give a score of 0.15.
The script loads a page with a banner that appears at the top after 400 ms and pushes everything down. It reads the shift entry from the browser, then computes the two fractions by itself from the rectangles in the entry.
js
// impact fraction: area covered by the moved elements before and after,// as a share of the viewport. distance fraction: the biggest move over// the larger viewport side. The score is their product.const covered = new Uint8Array(W * H)
let move = 0for (const { before, after } of shift.sources) {
for (const r of [before, after]) {
const y1 = Math.min(H, Math.round(r.y + r.height))
const x1 = Math.min(W, Math.round(r.x + r.width))
for (let y = Math.max(0, Math.round(r.y)); y < y1; y++) {
for (let x = Math.max(0, Math.round(r.x)); x < x1; x++) {
covered[y * W + x] = 1
}
}
}
for (const edge of ['top', 'bottom', 'left', 'right']) {
move = Math.max(move, Math.abs(after[edge] - before[edge]))
}
}
const impact = covered.reduce((a, b) => a + b, 0) / (W * H)
const distance = move / Math.max(W, H)
console.log('elements that moved :', shift.sources.length)
console.log('impact fraction :', impact.toFixed(3))
console.log('largest edge move :', move.toFixed(1), 'px')
console.log('distance fraction :', distance.toFixed(3))
console.log('impact x distance :', (impact * distance).toFixed(4))
console.log('reported by Chrome :', shift.value.toFixed(4))
p4b.mjs: compute the score from the rectangles.
text
elements that moved : 1
impact fraction : 0.623
largest edge move : 88.0 px
distance fraction : 0.138
impact x distance : 0.0857
reported by Chrome : 0.0857
Output (Chrome 157, 360 by 640 viewport)
The computed score equals the reported one. The moved element is the body: its rectangle before and after covers 62% of the viewport. Its bottom edge moved 88 px, which is the 80 px banner plus 8 px because the body margin no longer collapses into the heading margin, and 88 divided by 640, the larger side, is 0.138. The product is 0.0857. web.dev defines the distance as the largest move of any unstable element, and the script reads that as the largest move of any edge of a rectangle.
Common causes and fixes
Shifts happen when something takes up space it did not have a moment earlier. The script below loads five small pages in a phone-sized viewport and sums the shift scores of each.
page shifts CLS
image, no size 10.1227
image width and height 00.0000
image aspect-ratio 00.0000
banner pushes content 10.0857
banner in reserved slot 00.0000
Output (Chrome 157, 360 by 640 viewport)
An image with no size added 0.1227 when it loaded, over the 0.1 target by itself, because the browser did not know how tall it would be and the text below jumped down by about 200 px, the height of the image. The same image with width and height attributes caused no shift: the browser uses the two numbers to work out the aspect ratio and reserves the space before the file arrives. Setting aspect-ratio in CSS does the same job when the width comes from the layout. A banner that pushed the content down scored 0.0857, and the same banner in a slot with a reserved height scored zero. Layout-shift scores vary between runs. In ten runs of this script on this machine the image page scored 0.1227 eight times and 0.0000 twice, and the banner page scored 0.0857 every time. A real page varies more: the news feed chapter later in the course measured anything from 0.000 to 0.447 for one setup. Read each figure as one sample, and compare the pages rather than the digits.
Cause
Fix
Images and video without dimensions
width and height attributes, or aspect-ratio in CSS
Content inserted above existing content
reserve the space, or insert below the viewport
Ads and embeds that resize
a container with a fixed or minimum size
A web font that swaps in
a fallback font with matching metrics through size-adjust, and early font loading
Animations that change layout
animate transform, not top, left, width or height
Shifts that follow a click, tap or key press within 500 ms are excluded, because the user asked for them, flagged by the hadRecentInput field. Scrolling, dragging and pinch-zoom do not count as input, so a shift during them still counts.
Session windows
A page can live for hours, and a few small shifts spread across that time should not add up to a failure. CLS therefore uses session windows. A window is a group of shifts where each follows the previous one in under a second, and the window never lasts longer than five seconds. The page's CLS is the sum of the worst window, not the sum of all shifts.
js
// CLS is the largest session window, not the sum of every shift.// Invented shifts: [time in ms, score].const shifts = [[300, 0.04], [700, 0.05], [1100, 0.03],
[3600, 0.08], [4300, 0.07], [8000, 0.10]]
const windows = []
let cur = nullfor (const [t, value] of shifts) {
const gapOk = cur && t - cur.last < 1000// gap under 1 sconst lengthOk = cur && t - cur.first <= 5000// window up to 5 sif (gapOk && lengthOk) { cur.sum += value; cur.last = t }
else { cur = { first: t, last: t, sum: value }; windows.push(cur) }
}
const total = shifts.reduce((sum, [, v]) => sum + v, 0)
windows.forEach((w, i) => {
console.log(`window ${i + 1}: ${w.first}-${w.last} ms,`,
`sum ${w.sum.toFixed(2)}`)
})
const largest = Math.max(...windows.map((w) => w.sum))
console.log('sum of every shift:', total.toFixed(2))
console.log('CLS (largest window):', largest.toFixed(2))
p4c.mjs: group invented shifts into windows.
text
window 1: 300-1100 ms, sum 0.12
window 2: 3600-4300 ms, sum 0.15
window 3: 8000-8000 ms, sum 0.10
sum of every shift: 0.37
CLS (largest window): 0.15
Output (Node 24)
The six invented shifts sum to 0.37, which would be a poor score if every shift counted. They form three windows, and the worst one totals 0.15, so the CLS is 0.15. That is above 0.1, so the page needs work, but it is not poor. It also shows why fixing the biggest burst is worth more than chasing every small shift.
Lab runs miss most of this, because they capture shifts during load and a field user may scroll, open menus and wait for lazy content. web.dev recommends measuring CLS in the field with the web-vitals library for that reason. The hadRecentInput flag and window rule above are what the library applies for you.
An image has no width or height. Why does it cause a shift when it loads?
The browser does not know its height until the file arrives, so it reserves no space and the content below moves.
The run showed 0.1227 for that page and zero when the attributes were present; shift scores vary between runs, so treat the figure as one sample.
How is CLS computed from many shifts over a long session?
Shifts are grouped into windows: gaps under 1 s, at most 5 s long.
CLS is the sum of the worst window, not of all shifts.
Why animate transform instead of top or height?
Changing layout properties moves other elements and counts as shifts.
transform does not change layout, so nothing else moves.
Part 5 · The cost of JavaScript
Bytes that must run
A byte of JavaScript costs more than a byte of image. An image is downloaded and decoded, but it runs no code of its own. A script is downloaded, then parsed, compiled and executed, and that work competes with input handling on the main thread. A mid-range phone has less processing power than the machine you develop on, so the same bundle takes longer there.
That is why a JavaScript budget is set tighter than a budget for other bytes, and why INP often worsens as an app grows. Three techniques cut the cost. Send less code by removing what is unused. Send code later, so only what the first screen needs arrives first. Run less code at load, by deferring work that can wait.
Technique
What it does
Cost to you
Tree shaking
the build drops exports nobody imports
needs ES module syntax and side-effect-free code
Code splitting
the build makes separate files that load on demand
a delay the first time the feature is used
Lazy work at load
defers analytics, widgets and non-visible features
must handle the not-yet-loaded state
Fewer dependencies
drops a large library for a small one or a native API
rewriting and testing
The sections below use a real Vite 8 build, so the sizes are measured, not estimated.
Tree shaking and code splitting
The sample app has a utility file with two exports, only one of which is used, and a report module holding 3,000 invented order rows, about 220 KB of code. One entry imports the report at the top of the file. The other loads it with a dynamic import() when a button is clicked.
# Build the same page twice: report.js imported statically, then lazily.
strip() { # drop colour codes and progress lines
sed 's/\x1b\[[0-9;]*m//g' |
grep -vE '^(transforming|rendering|computing)'
}
for v instatic split; do
echo "== ENTRY=$v vite build"
ENTRY=$v npx vite build 2>&1 | strip
done
echo "== is the unused export in the output?"
grep -c NEVER_USED_MARKER dist-*/assets/*.js |
sed 's/^.*assets\//assets\//'
build.sh: build both entries, then search the output.
text
== ENTRY=static vite build
vite v8.3.6 building client environment for production...
✓ 6 modules transformed.
dist-static/static.html 0.21 kB │ gzip: 0.17 kB
dist-static/assets/static-DtvC8Stl.js 223.62 kB │ gzip: 89.17 kB
✓ built in 54ms
== ENTRY=split vite build
vite v8.3.6 building client environment for production...
✓ 7 modules transformed.
dist-split/split.html 0.21 kB │ gzip: 0.17 kB
dist-split/assets/split-wsgcX4bd.js 2.66 kB │ gzip: 1.26 kB
dist-split/assets/report-DlnFCoZ8.js 222.72 kB │ gzip: 88.47 kB
✓ built in 61ms
== is the unused export in the output?
assets/report-DlnFCoZ8.js:0
assets/split-wsgcX4bd.js:0
assets/static-DtvC8Stl.js:0
Output (vite 8.3.6, sizes in kB)
The static build produces one file of 223.62 kB, 89.17 kB after gzip. The split build produces two: a 2.66 kB entry and a 222.72 kB chunk for the report. The count at the bottom is the tree-shaking check: the unused helper's marker string appears in none of the files, so the bundler left it out. As a check on the check, a third entry that does call the helper was built once on the side, and its bundle contains the marker once, so a zero means the helper really was removed. Vite 8 is a recent major release, and the numbers belong to that version.
A dynamic import() returns a promise and tells the bundler to put the imported module in its own file. The user pays for it once, the first time the feature is used, and the browser keeps the file afterwards. Split at natural boundaries such as routes, tabs, dialogs and heavy widgets, not at every function: too many small files cost round trips.
Compression on the wire
Whatever you ship is also compressed in transit. The browser sends an Accept-Encoding header listing the algorithms it can decode, such as gzip and br (Brotli). The server picks one, compresses the body, names it in Content-Encoding and adds Vary: Accept-Encoding so that caches keep one copy per encoding. MDN recommends it for text such as HTML, CSS, JavaScript and JSON, and says to skip files that are already compressed, such as images, audio and video. The script compresses the static bundle both ways with the zlib module that ships with Node.
static-DtvC8Stl.js
coding bytes of raw
none 223629100.0 %
gzip 98653438.7 %
brotli 117451833.3 %
Output (Node 24)
Gzip at its highest level left 38.7% of the bytes and Brotli at its highest quality left 33.3%, about 12 KB less than gzip for this file. Vite's own report gave 89.17 kB for the same file because it estimates with its own settings, so expect small differences between tools. The numbers belong to this bundle: random order ids compress worse than typical code. Compression cuts download time only. The browser unpacks the file and then parses and runs all 2,23,629 bytes, so it does nothing for the run cost described at the start of the lesson.
What the browser fetches
A script loads each build in Chrome from a local server and records which JavaScript files are fetched at load and after the click.
js
const browser = await launch()
for (const which of Object.keys(dirs)) {
const page = await (await browser.newContext()).newPage()
const loaded = []
page.on('response', async (r) => {
if (!r.url().endsWith('.js')) returnconst size = (await r.body()).length
loaded.push(`${r.url().split('/').pop()} (${size} bytes)`)
})
await page.goto(`http://127.0.0.1:55837/${which}/`)
await sleep(500)
console.log(`${which}, at load:`, loaded.join(', '))
const before = loaded.length
await page.click('#open')
await sleep(500)
console.log(`${which}, after click:`,
loaded.slice(before).join(', ') || 'no new script')
}
await browser.close()
server.close()
p5b.mjs: watch the responses.
text
static, at load: static-DtvC8Stl.js (223629 bytes)
static, after click: no new script
split, at load: split-wsgcX4bd.js (2661 bytes)
split, after click: report-DlnFCoZ8.js (222721 bytes)
Output (Chrome 157)
The static page downloads all 2,23,629 bytes at load, before the user has asked for the report, and the click needs nothing more. The split page downloads 2,661 bytes at load, and the report only when the button is clicked. The first screen of the split page has 98.8% less script to download, parse and run, and the price is a short wait on the first click, which the interface can cover with a loading state or by fetching the chunk when the pointer approaches the button.
Two cautions. Splitting moves cost, it does not remove it: a heavy feature that every user opens still downloads, so count by how many users reach it. And tree shaking depends on how libraries are written. A library that is not published as ES modules, or whose imports have side effects, may be included whole. Check the build report after adding a dependency, the same way you check tests after changing code.
Why does a 200 KB script hurt a phone more than a 200 KB image?
The script must also be parsed, compiled and run, mostly on the main thread.
The image is only decoded. It runs no code, so it cannot hold the main thread the way a script can.
Gzip cut the 2,23,629-byte bundle to 86,534 bytes. Does the phone now do about 61% less parse and run work?
No. Compression only shortens the download. The browser unpacks the file and parses and runs all 2,23,629 bytes.
To cut run work, send less code with tree shaking, splitting or fewer dependencies.
In the run, what did splitting change at page load and on the click?
At load the page fetched 2,661 bytes instead of 2,23,629.
The 2,22,721-byte report chunk was fetched only when the button was clicked.
Part 6 · Images and fonts
Sending the right image
Images are often the largest files on a page, and the biggest LCP lever once the image is found early. Two decisions matter: how many pixels to send and in what format.
The srcset attribute lists the files you have, each with its real width in pixels and a w after the number. The sizes attribute tells the browser how wide the image will be shown, as a list of media conditions and widths. The browser takes the first matching condition, multiplies the slot width by the screen's pixel density, and fetches the file that covers that many pixels. The script checks the choice on four screens.
A phone 360 px wide with a pixel density of 3 has 1,080 device pixels across, so Chrome fetched the 1,200 px file. At density 1 it needed 360 and chose the 400 px file. On a wide desktop screen the sizes list says the image shows at 400 px, so it fetched the 400 px file at density 1 and the 800 px file at density 2. Without sizes the browser assumes the image fills the viewport and tends to fetch more than it needs. Because the choice is the browser's, you provide a ladder of widths and an honest sizes.
MDN's guide says WebP and AVIF generally compress better than JPEG and PNG. Lossy WebP is on average 25 to 35% smaller than JPEG at similar quality, and lossy AVIF is around 50% smaller, though AVIF has less history in browsers. Serve them with a fallback inside a picture element, so a browser that cannot decode the first type takes the next. The snippet is markup only: it needs real encoded files, and this lab did not encode any.
Not run: the files do not exist here. The pattern follows MDN.
Lazy loading below the fold
loading="lazy" tells the browser to fetch an image only when it is near the viewport. It saves bytes for content the user may never reach, and it is the wrong choice for the LCP image. The script loads 20 tall images in a phone-sized viewport, eager and lazy, and counts the files the server received.
js
for (const mode of ['eager', 'lazy']) {
requested.clear()
const context = await browser.newContext({
viewport: { width: 360, height: 640 } })
const p = await context.newPage()
await p.goto(`http://127.0.0.1:55836/?${mode}`)
await sleep(800)
const log = [`${mode.padEnd(6)} load ${requested.size}`]
await p.evaluate(() => scrollTo(0, document.body.scrollHeight))
await sleep(800)
log.push(`jump to end ${requested.size}`)
for (let y = 12000; y >= 0; y -= 600) {
await p.evaluate((top) => scrollTo(0, top), y)
await sleep(100)
}
await sleep(500)
log.push(`scroll back ${requested.size}`)
console.log(log.join(' | '))
await context.close()
}
p6b.mjs: count requests while scrolling.
text
eager load 20 | jump to end 20 | scroll back 20
lazy load 4 | jump to end 8 | scroll back 20
Output (Chrome 157)
The eager page requested all 20 images at load. The lazy page requested 4, the ones on or just below the first screen. Jumping straight to the end brought the count to 8, because only the images near the end were close to the viewport. Scrolling back up in steps fetched the rest. The browser chooses the distance at which it starts fetching, so a fast scroll can reach an image before it is ready. A placeholder with a reserved size, as in the layout shift lesson, keeps that moment from shifting the page.
Fonts
A web font is a file the page needs before it can show text in its chosen face. The font-display descriptor says what to do while it loads. block hides text for a short time, two to three seconds in the worst case. swap shows the fallback font straight away and swaps when the web font arrives, which can shift the layout. fallback blocks for 100 ms and gives the swap a three-second window. optional waits about 100 ms and then keeps the fallback if the font is not ready, so it causes no shift but may never show the web font on a slow first visit. This lab did not measure the display behaviour, which web.dev documents.
A font file includes every glyph of its script, so a Latin and Devanagari family can be large. Subsetting splits it into files by character range. The unicode-range descriptor tells the browser which characters each file covers, and the browser downloads a file only when the page contains one of them. The script uses two @font-face rules with placeholder files that are not real fonts, because only the requests matter.
English only: font files requested: latin.woff2
English and Hindi: font files requested: devanagari.woff2, latin.woff2
Output (Chrome 157)
A page with English text requested only the Latin file. Adding one Hindi word made it request the Devanagari file as well. Readers of English-only pages never pay for the Devanagari glyphs. preload ignores unicode-range, so web.dev advises preloading only the most important fonts, in a single format (WOFF2), rather than every subset.
A phone is 360 px wide with a pixel density of 3, and the slot is full width. Which file from 400, 800 and 1,200 px does the browser pick, and why?
The 1,200 px file, because the screen has 1,080 device pixels across and it is the smallest file that covers them.
The run showed b-1200.png.
Why is loading="lazy" right for the 15th image on a page but wrong for the hero?
The 15th image may never be seen, so deferring it saves bytes.
The hero is the LCP element, and deferring its fetch delays LCP, as the LCP lesson measured.
What does unicode-range change about which font files a page downloads?
The browser downloads a file only if the page contains characters in its range.
In the run, the Devanagari file was requested only for the page with a Hindi word.
Part 7 · Caching
Headers that decide
The fastest request is the one that never leaves the machine. HTTP caching is controlled by response headers, and the right setting depends on whether the URL changes when the content does.
Files whose names contain a hash of their content, such as app.3f9a1c.js, get a new URL whenever they change, so an old URL can be cached forever. Cache-Control: max-age=31536000, immutable says the file is fresh for a year, and immutable tells the browser not to revalidate it even on reload. The HTML page that names those files cannot change its own URL, so it needs the opposite rule: Cache-Control: no-cache. Despite the name, no-cache allows storing the response. It says the cache must check with the server before reusing it.
Directive
Meaning
max-age=N
fresh for N seconds; reuse without asking
immutable
will not change while fresh; do not revalidate
no-cache
may store, but revalidate before every reuse
no-store
do not store at all
public / private
whether shared caches such as a CDN may store it
A check with the server is a conditional request. The server sends a validator, an ETag, with the first response. The browser sends it back in If-None-Match. If the file has not changed, the server answers 304 Not Modified with no body, and the browser reuses its copy. Without any Cache-Control header a cache may still reuse a response for a heuristic period, about a tenth of the time since Last-Modified, so always set the header yourself.
What the server sees
The script runs a small Express 5 server and lets Chrome visit it three times. The HTML has no-cache. The script file has a build number in its name and the one-year immutable rule. Between the second and third visits the server "deploys" a new build.
visit 1
GET / -> 200
GET /assets/app.b1.js -> 200
visit 2, same build
GET / (If-None-Match) -> 304
visit 3, after a deploy
GET / (If-None-Match) -> 200
GET /assets/app.b2.js -> 200
Output (Chrome 157, Express 5.3.0)
Visit 1 downloads both files. In visit 2 the browser revalidates the HTML, sending If-None-Match, and receives a 304 with no body. The script is not requested at all: the server never saw it, because the browser had a fresh copy. After the deploy, the conditional request for the HTML returns 200 with the new page, which names app.b2.js. That file is a different URL, so it is fetched, and the old one is never asked for again.
Animated sceneA repeat visit0:16
Watch for which request reaches the server on a repeat visit
Read it as steps
The HTML revalidates with a 304. The hashed script comes from the browser cache.
The scene follows visit 2. The server is asked one small question about the page and nothing about the script. That is the reason to put hashes in file names: they let you cache the heavy files without risking stale code. A CDN is a shared cache that obeys the same headers, so the same rules apply, but this lab did not run one.
Service workers
The service worker from the fundamentals chapter is a script that sits between the page and the network and can answer requests itself. It lets an app work offline and choose its own caching strategy. It registers once, installs, and activates, and it runs only in a secure context, which includes localhost. The script below caches the page and its script at install and answers requests for them from the cache. For the price API it uses stale-while-revalidate, the policy from the fundamentals chapter: answer from the cache at once, and fetch a fresh copy behind the scenes.
The server increments version on every request to the price endpoint. The first call finds nothing in the cache and goes to the network, giving version 1. The second call returns the cached version 1 at once and starts a refresh. The third call, after the refresh, returns version 2, and it triggers another refresh that stores version 3. With the browser set offline, the call is answered from the cache with version 3, and reloading the page still works, because the worker serves the page and script from the cache.
Choosing a strategy
Each strategy suits a kind of resource. Cache first suits files that never change at a given URL. Stale-while-revalidate suits data where slightly old is fine. Network first, falling back to the cache, suits content that should be fresh when possible. The cost is a new thing to keep correct: an old worker can serve stale code until a new one takes over, so version your caches and delete old ones when the worker activates.
Term
Meaning
TTFB
time from navigation start to the first byte of the response
Long task
a main-thread task over 50 ms
Yielding
letting the browser run other work between pieces of a task
Session window
a group of layout shifts under 1 s apart, at most 5 s long
Validator (ETag)
a token the server uses to say a cached copy is still current
Virtualisation
rendering only the rows that are on screen
Why is it safe to cache app.b1.js for a year but not the HTML that names it?
The file's URL changes when its content changes, so an old URL never serves new code.
The HTML keeps one URL, so it must be revalidated to pick up new file names.
What did the second visit in the run send to the server, and what came back?
A conditional request for the HTML with If-None-Match.
A 304 with no body. The script was not requested at all.
In the run, why did the third price call return version 2 when the second returned version 1?
The second call returned the cached copy and started a refresh.
The refresh had finished by the third call, so the cache held version 2.
Part 8 · Large lists
Why long lists are slow
A table of orders, a chat history or a product grid can have thousands of rows. Browsers handle that badly if every row is in the page, because each element adds to style calculation, layout and memory, and layout runs again whenever something changes. The fix is to render less.
Three levels of response exist. First, keep the list short with pagination or a limit and a "show more" control. Second, let the browser skip work for rows that are off screen with content-visibility. Third, virtualise: render only the rows in view plus a small margin, and fake the rest of the scroll height with an empty spacer.
The test page has 10,000 rows of fixed height 40 px inside a 600 px scroll box. The first mode adds every row. The second adds every row with content-visibility: auto and a placeholder size. The third renders a window of about 25 rows and replaces them on scroll.
const t1 = performance.now() // DOM nodes created
list.getBoundingClientRect() // force style and layoutconst t2 = performance.now()
return {
build: t1 - t0, layout: t2 - t1,
nodes: document.getElementsByTagName('*').length,
}
}
p8.html: the timing.
Measuring the three
Each mode runs in a fresh page with the CPU slowed four times. The script reports the number of elements and two times: how long the browser took to create the nodes, and how long it took to run style and layout when forced.
mode elements build ms layout ms
all 10,000 rows 1000761375
content-visibility: auto 1000765177
windowed list 34439
windowed list after scrolling to 200,000 px:
first row "Order 4996, Pune, ₹5950", 34 elements
Output (Chrome 157, lab, this machine, 4x CPU throttling)
All 10,000 rows put 10,007 elements in the page and needed 375 ms of layout. With content-visibility: auto the element count is the same, but layout dropped to 177 ms because the browser skipped the contents of rows far from the viewport. The windowed list had 34 elements and its layout took 39 ms. Creating the nodes cost about 60 to 65 ms for the first two and 4 ms for the window. Across four runs on this machine the layout time ranged from 375 to 605 ms for all rows, 177 to 236 ms with content-visibility and 28 to 47 ms for the window, so the numbers move a lot but the order never changed.
After scrolling the windowed list to 2,00,000 px, the first rendered row was "Order 4996" and the page still held 34 elements. The viewport begins at row 5,001, and five rows of overscan above it are rendered too. The overscan matters: without a few extra rows each side, a quick scroll shows blank space before the next paint.
Choosing and the cost of virtualising
content-visibility: auto is the cheapest change: one rule, and the content stays in the DOM. MDN lists it as newly available in Baseline since September 2024. Skipped content remains available to find in page, to tab focus and to the accessibility tree, and contain-intrinsic-size gives each skipped row a placeholder height so the scrollbar stays stable. It still keeps 10,000 nodes in memory.
Virtualisation is the strongest change and has the most cost. The browser's find-in-page cannot see rows that do not exist. Keyboard focus is lost when a focused row is removed. Screen readers get an incomplete list unless you tell them how many items exist. Row heights must be known or measured, and scroll position and selection must be restored. A common compromise is to start with pagination or content-visibility, and add virtualisation only when measured numbers demand it.
Choice
Works well for
Watch out for
Pagination or "load more"
content users scan page by page
losing the sense of the whole list
content-visibility: auto
long documents and lists in the low thousands
memory still grows; placeholder sizes must be sensible
Virtualisation
tens of thousands of rows, tables, chat history
find in page, focus, accessibility and variable heights
Whichever you choose, give the list an accessible name, set aria-setsize and aria-posinset on rows when they are virtualised so assistive technology knows the real size, and keep the row markup simple. The work per row matters as much as the count: a row with a hundred elements and three event listeners costs far more than a plain one.
The windowed list has 34 elements for 10,000 rows. How does the scroll box still look 4,00,000 px tall?
A spacer element is given the full height, 10,000 rows of 40 px.
Only the rows near the scroll position are rendered inside it.
What did content-visibility: auto change in the run, and what did it leave the same?
It cut layout time because rows far from the viewport were skipped.
The element count stayed at 10,007, so memory use is similar.
Name two things virtualisation breaks that you must restore yourself.
Find in page and keyboard focus on removed rows.
Screen reader list size, unless aria-setsize and aria-posinset are provided.