Project: rescue a slow app's INP
Find the slowest taps in a heavy single-page app from field data, reproduce them in the lab, then fix each one: yield, move scoring to a worker, render less.
- 01Find the worst interactionsGroup your RUM's INP by the element it happened on, see which part was longest, and reproduce it in the lab with long animation frames.
- 02Match each fix to its partYield and break up work for input delay and long handlers, move pure scoring to a worker, and render less for presentation delay.
- 03Prove it, in the lab and the fieldMeasure every task before and after each step the same way, and check the field's p75 for the whole app.
From a slow tea finder to a fast one, a part at a time
Leaf and Kettle has a new page: the Tea finder. It's a single-page app, a page that changes itself with JavaScript instead of loading new pages. It holds all 5,000 of the shop's teas. You can search them, sort them by price, compare two, and add any of them to your cart.
Asha tries it on her phone. She types mint, and the letters crawl into the box. She taps Sort by price, and nothing moves for most of a second. She taps Add on the first tea while the list is still filling, and waits again.
Ravi built the store's own RUM in lesson 45.2. RUM, real user monitoring, means measuring real visits. He adds the finder to it. After one week, the finder's INP is poor. INP, Interaction to Next Paint, is roughly a visit's slowest tap, click or key press: the time until the page showed its answer (lesson 26.1). So which taps are slow? And why each one?
Here is where the project ends. These are the finder's numbers from the field, a week before the project and a week after it:
// The Tea finder's INP: the p75 of each week's visits, in ms. Week 1 met it before the project, week 2 after.const p75 = { week1: 1128, week2: 56 };const rate = (ms) => (ms <= 200 ? "good" : ms <= 500 ? "needs improvement" : "poor"); for (const [week, ms] of Object.entries(p75)) { console.log(`${week}: ${ms} ms, ${rate(ms)}`);}- Line 1 is a comment. Each number is a p75: three visits in four were at that number or better (lesson 3.4). A millisecond (ms) is a thousandth of a second.
- Line 2 holds the p75 of each week. Line 3 rates a time with Google's lines: good up to 200 ms, poor over 500 ms.
- Lines 5 to 7 print
week1: 1128 ms, poorandweek2: 56 ms, good.
Four tasks were slow, and each was slow for its own reason. Here is each one in the lab, on a phone like Asha's, before the project and after it:
Each bar is one task's INP, split into its three parts (lesson 26.2). The input delay is the wait before the tap's code can start. Processing is the tap's own code. The presentation delay is the time to draw the new screen. Add mostly waited. Compare and the search mostly worked. Sort mostly drew.
A busy clinic has one nurse at the door. She doesn't treat patients in the order they came. She asks each one where it hurts, and sends the worst cases in first. The doctor runs a test to find the cause, treats it, and checks again before the next patient.
- In real life: The waiting room's patients
- In web performance: The visits, each with its slowest tap
- In real life: Asking where it hurts
- In web performance: INP's three parts, and the element tapped
- In real life: The worst cases go first
- In web performance: The element with the highest p75
- In real life: The test that finds the cause
- In web performance: The lab: a trace and the long animation frames
- In real life: Checking again after the treatment
- In web performance: Measuring every task again, the same way
Let the field name the slowest interactions and their longest part. Reproduce each one in the lab to find the code behind it. Then fix that part with the tool that matches it, and measure again. Input delay and long handlers call for yielding. Pure data work can move to a worker. Presentation delay calls for rendering less.
The project has one search and three steps:
- Find the worst interactions: in the field first, then in the lab.
- Step 1: yield, and break up long work, for Add and Compare.
- Step 2: debounce the search, and score it in a worker.
- Step 3: render less, for Sort by price.
Build each step on your own copy, and compare it with the course's. Each version is published in its own folder. Serve the files the way lesson 1.4 showed, and save page.html as index.html:
- Before: app.js, page.html, styles.css, teas.json.
- Yielding: app.js, page.html, styles.css, teas.json.
- Worker: app.js, page.html, search-worker.js, styles.css, teas.json.
- Rendering less: app.js, page.html, search-worker.js, styles.css, teas.json.
How the course recorded it
- The app: each version served over HTTPS at a made-up address, shop.example/finder/, gzipped as most hosts send files.
- The field: 120 visitors a week, 84 on phones and 36 on computers, each with its own CPU speed and network, drawn the way lesson 13.1 drew them. Week 1 met the finder before the project, and week 2 after it. Each visit did one task. It typed a word, a key every 120 ms. Or it tapped Add 400 ms after the catalogue arrived. Or it ticked two teas and tapped Compare, or tapped Sort by price. Lesson 45.2's
rum.jsand collector stored every visit. - The lab: Chrome for Testing 157.0.8103.52 as Asha's phone: Lighthouse's phone screen, DevTools' Slow 4G network and the CPU 4× slower. Each task ran 5 times on each version, taking turns, after one round that wasn't kept. Every run was traced. web-vitals' attribution build and the long animation frames reported each task's INP.
- The input: mouse presses and key presses sent through Chrome's DevTools protocol, which passes them straight to the page.
- The worker: DevTools can slow the page's main thread, but not a worker (lesson 27.4). So while recording, the worker scored each search as many times over as the CPU was slowed: 4 times in the lab.
Find the worst interactions
The field knows which taps were slow, and for whom. The lab can show why. web.dev's guide to INP starts the same way: field data first, then the lab. Lesson 26.3 took that path for one tap. Here there are four.
Send the finder's numbers home
The finder gets the same RUM line as the store's other pages, at the end of its body. rum.js and the web-vitals library stay where lesson 45.2 put them, at the store's root:
<ul id="list"></ul> <script type="module" src="/rum.js" async></script></body>Line 2 is new. Its path starts with /, so it finds rum.js at the store's root from any page. The collector needs one change too:
// collector.mjs: the finder is a page the collector knows.const PAGES = ["/", "/about.html", "/finder/"];The collector stores any other path as "other". Line 2 adds /finder/ to the pages it knows.
Group each visit's INP by element
Each beacon carries the visit's INP with its attribution: the element tapped, and the three parts. The web-vitals library works them out from Event Timing, the browser's record of each event. Ravi writes one more small script, worst.mjs, next to lesson 45.2's queries.js:
// worst.mjs: which interactions make the Tea finder's INP, and which part of each is slowest.// node worst.mjs this week// node worst.mjs 1 last weekimport { readFileSync } from "node:fs";import { parse, percentile, weekOf } from "./queries.js"; const PARTS = ["input delay", "processing", "presentation delay"];const beacons = parse(readFileSync("beacons.jsonl", "utf8"));const now = Math.max(...beacons.map((beacon) => beacon.time));const visits = weekOf(beacons, now, Number(process.argv[2] ?? 0)).filter((beacon) => beacon.page === "/finder/" && beacon.inp); // Each visit's INP, grouped by the element it happened on.const byElement = {};for (const { inp } of visits) (byElement[inp.element] ??= []).push(inp);- Lines 1 to 3 say how to run it: for this week, or for the week before.
- Line 5 reuses three functions from
queries.js:parse(),percentile()andweekOf(). - Lines 8 and 9 read every stored beacon, and take the newest one's time as now.
- Line 10 keeps one week's visits to the finder that had an INP.
- Lines 13 and 14 sort each visit's INP into a group, by its element.
??=starts an empty group the first time.
console.log(`p75 INP: ${percentile(visits.map(({ inp }) => inp.value), 0.75)} ms, from ${visits.length} visits`);const rows = Object.entries(byElement).map(([element, inps]) => { // In each visit, the part that took longest. Then the part that was longest most often. const longest = inps.map(({ parts }) => parts.indexOf(Math.max(...parts))); const counts = PARTS.map((_, part) => longest.filter((index) => index === part).length); const top = counts.indexOf(Math.max(...counts)); return { element, count: inps.length, p75: percentile(inps.map(({ value }) => value), 0.75), part: PARTS[top], times: counts[top] };});for (const row of rows.sort((a, b) => b.p75 - a.p75)) { console.log(`${row.element} p75 ${row.p75} ms visits ${row.count} longest part: ${row.part} (${row.times} of ${row.count})`);}- Line 1 prints the p75 of all the week's visits.
- Line 4 finds, in each visit, which of the three parts was the longest.
- Lines 5 and 6 count how often each part was the longest, and keep the winner.
- Line 7 makes one row per element. Lines 9 and 10 print the rows, the highest p75 first.
Here is what it printed over week 1's beacons:
p75 INP: 1128 ms, from 120 visits#list>li.tea>button.add p75 1504 ms visits 30 longest part: input delay (21 of 30)#sort-price p75 1248 ms visits 30 longest part: presentation delay (30 of 30)#compare p75 1224 ms visits 30 longest part: processing (30 of 30)#search p75 440 ms visits 30 longest part: processing (14 of 30)Line 1 is the whole week. Each line after it groups the visits whose slowest tap was on one element. #list>li.tea>button.add is the Add button in any row. It names the button's class and its parents, because the buttons have no id. Each row also says which part was longest. Why it matters: the element says which task to look at, and the part says which kind of fix to reach for.
Reproduce each one in the lab
The field says where and which part. To see which code, Ravi makes each task happen in the lab, on a slow phone (lesson 26.3). The trace's Interactions track shows each tap. And the long animation frames name the scripts that ran during it (lesson 11.5). The web-vitals attribution build picks the longest one, and says which of the three parts it ran in. Read each row across:
| Task | INP in the lab | Its longest part | The longest script, and the part it ran in |
|---|---|---|---|
| Typing in the search box | 400 ms | processing: 299 ms. | INPUT#search.oninput, in the processing. It ran 127 ms. |
| Add, while the list is still filling | 1,368 ms | input delay: 1,250 ms. | TimerHandler:setTimeout, in the input delay. It ran 1,506 ms, 1,351 ms of them forced style and layout. |
| Compare | 1,168 ms | processing: 1,049 ms. | BUTTON#compare.onclick, in the processing. It ran 1,033 ms. |
| Sort by price | 920 ms | presentation delay: 660 ms. | BUTTON#sort-price.onclick, in the processing. It ran 209 ms. |
The longest script turns each part into a lead. Add's wait was a timer, set by the finder's own start-up code. The search and Compare spent their time in their own handlers. Sort's handler ran for 209 ms, and most of the tap came after it. Why it matters: a part says what kind of time it was. Only the lab can say whose code it was.
The playground holds every task at every checkpoint. Start on Before, and come back to it after each step:
Before- Typing in the search box400 ms = 101 + 299 + 0
#search(keyboard), 40,028 elements in the page. Longest script:INPUT#search.oninput, in the processing. It ran 127 ms. - Add, while the list is still filling1,368 ms = 1,250 + 24 + 95
#list>li.tea>button.add(pointer), 40,020 elements in the page. Longest script:TimerHandler:setTimeout, in the input delay. It ran 1,506 ms, 1,351 ms of them forced style and layout. - Compare1,168 ms = 5 + 1,049 + 114
#compare(pointer), 40,046 elements in the page. Longest script:BUTTON#compare.onclick, in the processing. It ran 1,033 ms. - Sort by price920 ms = 42 + 218 + 660
#sort-price(pointer), 40,020 elements in the page. Longest script:BUTTON#sort-price.onclick, in the processing. It ran 209 ms.
Each bar is the task's INP in three parts: input delay, processing (shaded) and presentation delay. Under it: the element web-vitals named, and the longest script the long animation frames saw.
Step 1: yield, and break up long work
Two tasks waited for the finder's own JavaScript. Add waited for work that was already running. Compare's handler did all its work before it showed anything. Both are long tasks: jobs the main thread runs from start to end without stopping. The main thread is the one thread that runs the page's JavaScript, answers taps and draws the screen.
Add: the list fills in one long task
// Adds teas at the end of the list, and fits their names.function addRows(some) { list.insertAdjacentHTML("beforeend", some.map(row).join("")); fitNames([...list.querySelectorAll(".name")].slice(-some.length));} // The first screen of teas at once, then the rest straight after.addRows(teas.slice(0, 20));setTimeout(() => addRows(teas.slice(20)));- Lines 2 to 5 add some teas as rows at the end of the list, then fit their names.
- Line 8 adds the first 20 teas at once: a screenful.
- Line 9 adds the other 4,980 in a timer. A timer makes a new task, so the browser can paint the first screen before it. But that task runs for as long as all 4,980 rows take.
In the lab, that task ran for 1,506 ms. Asha's tap came 400 ms after the catalogue arrived, in the middle of it. Her tap waited 1,250 ms, then took 24 ms to run.
A car comes to a level crossing just as a long goods train starts to pass. The barrier stays down until the last wagon is through, however short the car's trip. If the railway ran the same wagons as short trains with gaps, the car could cross in the next gap.
- In real life: The goods train
- In the browser: The task that adds 4,980 rows
- In real life: A car at the barrier
- In the browser: Asha's tap, waiting
- In real life: The wait at the barrier
- In the browser: The input delay
- In real life: Short trains with gaps
- In the browser: Pieces of work, with a yield after each
To yield is to stop your work for a moment, so the browser can run something else, like a tap (lesson 27.2). Ravi cuts the work into pieces of about 50 ms, as lesson 27.3 did, and yields after each:
// Lets the browser handle input and draw a frame, then carries on (lesson 27.2).function yieldNow() { if (globalThis.scheduler?.yield) return scheduler.yield(); return new Promise((resolve) => setTimeout(resolve, 0));} // The first screen of teas at once, then the rest in pieces, yielding every 50 ms (lesson 27.3).async function addRest() { let start = performance.now(); for (let i = 20; i < teas.length; i += 100) { addRows(teas.slice(i, i + 100)); if (performance.now() - start > 50) { await yieldNow(); start = performance.now(); } }}addRows(teas.slice(0, 20));addRest();- Lines 2 to 5 are lesson 27.2's
yieldNow(). Line 3 usesscheduler.yield()where the browser has it. Line 4 falls back to a timer where it doesn't. - Line 9 notes when the piece started. Lines 10 and 11 add 100 rows at a time.
- Line 12 checks the piece's time. After 50 ms, line 13 yields, and line 14 starts the clock again.
- Lines 18 and 19 add the first screen at once, then start the rest.
Add's INP fell from 1,368 ms to 120 ms. Its input delay fell from 1,250 ms to 56 ms: the rest of the piece that was running. Here is the main thread around the tap, before and after:
The work didn't shrink. It still kept the main thread busy for most of the time shown. But it came in pieces, and the tap got in between two of them. Why it matters: yielding doesn't make work smaller. It lets a tap go first.
Compare: show the table, then yield
document.querySelector("#compare").addEventListener("click", () => { const chosen = [...picked].map((id) => teas[id]); panel.innerHTML = table(chosen, chosen.map(similarTo)); panel.hidden = false;});Line 2 finds the ticked teas. Line 3 builds the table, and finds three similar teas for each one first. similarTo() scores all 5,000 teas, the way the search does. Line 4 shows the panel. Nothing reached the screen until the scoring was done: 1,049 ms of processing.
Lesson 28.1 showed the fix: show the change first, then yield, then do the rest. In Chrome, the frame after a tap goes ahead of your next piece, so the change reaches the screen first.
document.querySelector("#compare").addEventListener("click", async () => { const chosen = [...picked].map((id) => teas[id]); panel.innerHTML = table(chosen); panel.hidden = false; await yieldNow(); const similar = []; for (const tea of chosen) { similar.push(similarTo(tea)); await yieldNow(); } panel.innerHTML = table(chosen, similar);});- Line 1 adds
async, so the handler can pause withawait. - Line 3 shows the table at once, with "Looking…" where the similar teas will go. Line 5 yields, so it can be painted.
- Lines 7 to 10 find each tea's similar teas, with a yield after each. Line 11 fills them in.
Compare's INP fell from 1,168 ms to 144 ms. But the scoring still ran after the paint, in long tasks: the longest took 511 ms. A tap in that time would wait, as Add did. Step 2 deals with it.
Try it on your own device. Each tap below runs 250 ms of pretend work, before the cart changes or after it:
Your browser times the tap with Event Timing, from your press to the next paint. Each tap runs 250 ms of pretend work. Switch ways, then tap again.
Step 2: debounce the search, and score it in a worker
After step 1, typing was still slow: 400 ms for the slowest key in the lab. Here is the search's handler:
document.querySelector("#search").addEventListener("input", (event) => { showSuggestions(scoreAll(teas, event.target.value).slice(0, 8));});Line 2 scores every tea on every input event, and shows the best 8. The input event fires each time the box's text changes. In the lab, one search ran for 127 ms, and a key came every 120 ms. So a key could wait for the search the key before had started. The slowest key waited 102 ms before its own search could begin.
The field's visitors had faster and slower phones than the lab. For them, the search's longest part was processing in 14 of 30 visits. In 11, it was presentation delay: drawing a page of 40,000 elements. Step 3 deals with that.
Two fixes fit, and Ravi makes both. The first is to search once the typing stops:
// Scoring runs in search-worker.js, on a thread of its own (lesson 27.4).const worker = new Worker("search-worker.js"); // Runs fn once the calls have stopped for `wait` ms (lesson 28.1).const debounce = (fn, wait) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), wait); };};const searchSoon = debounce((query) => worker.postMessage({ for: "search", query, count: 8 }), 250);document.querySelector("#search").addEventListener("input", (event) => searchSoon(event.target.value));- Lines 4 to 11 are
debounce(), as lesson 28.1 wrote it. Line 8 cancels the last timer, and line 9 starts a new one. Sofnruns only afterwaitms with no new call. - Line 12 makes
searchSoon(): 250 ms after the last key, it sends the search to a worker. Line 13 calls it on every key. - Line 2 starts the worker.
Debouncing is like a lift that waits until people stop stepping in before it closes its doors. The second fix moves the scoring itself. A web worker is a second thread that a page starts for its own JavaScript (lesson 27.4). It can't touch the page. The scoring doesn't need to: it takes teas and words, and gives back results.
// search-worker.js: scores teas for the Tea finder, on a thread of its own.const ready = fetch("teas.json").then((response) => response.json()); // … typosIn(), points() and scoreAll(), moved here as they were … // Each message asks for one search. The answer goes back with the same `for`.addEventListener("message", async ({ data }) => { const teas = await ready; postMessage({ for: data.for, results: scoreAll(teas, data.query).slice(0, data.count) });});- Line 2 fetches the catalogue in the worker. So the main thread never copies 5,000 teas into a message.
- Line 4 stands for the scoring functions, moved over from app.js as they were.
- Lines 7 to 10 answer each message. Line 9 sends back the best results, with the same
for, so the page knows what they're for.
There are no yields in the worker. Nothing else runs on its thread, so no tap waits for it. The HTML standard says workers allow "long tasks to be executed without yielding to keep the page responsive."
A shop assistant used to work out every customer's quote at the counter, while the queue grew. Now she slips each request under the back-office door, and serves the next customer. The clerk in the back does the sums and slips the answer back. The clerk can't serve anyone, but she doesn't need to.
- In real life: The shop assistant at the counter
- In the browser: The main thread
- In real life: The clerk in the back office
- In the browser: search-worker.js
- In real life: A note under the door, and one back
- In the browser: postMessage(), each way
- In real life: The next customer, served at once
- In the browser: The next key, handled at once
Compare sends its similar-teas searches to the worker too. The page takes every answer in one place:
// The worker's answers: suggestions for the search box, or one tea's similar teas.worker.addEventListener("message", ({ data }) => { if (data.for === "search") return showSuggestions(data.results); const cell = document.querySelector(`#similar-${data.for}`); if (cell) cell.innerHTML = names(data.results.filter(({ tea }) => tea.id !== data.for).slice(0, 3));});Line 3 shows the suggestions when the answer is for the search box. Lines 4 and 5 fill in one tea's similar teas, leaving the tea itself out.
The search task's INP fell from 400 ms to 120 ms. Here is the main thread while Asha typed mint, after step 1 and after step 2, and the worker's thread:
In the time shown, the main thread was busy for 619 ms after step 1, and for 280 ms after step 2. The worker did one search, after the typing stopped. Why it matters: the keys no longer wait for anything but their own frame.
Step 3: render less
One task was left: Sort by price, at 1,016 ms after step 2. Its processing took 222 ms. Its presentation delay was 753 ms. The page held 40,020 elements, and Sort moved all 5,000 rows. Chrome had to restyle and lay out every one of them before it could paint (lesson 31.3).
document.querySelector("#sort-price").addEventListener("click", () => { const rows = [...list.children].sort((a, b) => teas[a.dataset.id].cents - teas[b.dataset.id].cents); list.append(...rows);});Line 2 sorts the rows by price. Line 3 puts every one of them back, in the new order. But first, one more cost from the start-up.
Read first, then write
// Makes each name smaller where it doesn't fit its row.function fitNames(names) { for (const name of names) { if (name.scrollWidth > name.clientWidth) name.classList.add("small"); }}Line 4 reads a name's width, and makes the name smaller if it doesn't fit. Every hundredth tea is a Reserve, with a name too long for a phone's row. So a write came between two reads, 50 times at start-up. Each read after a write made Chrome lay out the page again, at once. That's layout thrashing (lesson 31.2). The long animation frame said it: of the start-up script's 1,506 ms, 1,351 ms were forced style and layout.
Someone rearranging a room moves one chair, then measures the whole room again before the next one. Fifty chairs take fifty measurings. Measure once, note every change, then move all the chairs, and the job takes one.
- In real life: Moving one chair
- In the browser: classList.add("small"): a write
- In real life: Measuring the whole room again
- In the browser: A layout, forced by the next read
- In real life: Measuring once, then moving every chair
- In the browser: Every read first, then every write
// Makes each name smaller where it doesn't fit its row: every read first, then every write (lesson 31.2).function fitNames(names) { const tooLong = [...names].filter((name) => name.scrollWidth > name.clientWidth); for (const name of tooLong) name.classList.add("small");}Line 3 reads every name's width first. Line 4 then makes the long ones smaller. To see what the thrashing cost on its own, the course ran the first version with only this change. The start-up script fell from 1,506 ms to 666 ms, and Add's INP from 1,368 ms to 528 ms.
Keep only the rows near the screen
Fewer elements would help every task. Lesson 28.2 tried content-visibility on a 3,000-row tea list. Chrome skipped the rows far from the screen, but the click still took just over 200 ms: every moved row was still a box to style and place. So Ravi goes further, with a virtual list. The teas stay as data, and only the rows near the screen are in the page (lesson 31.3).
// Only the rows near the screen are in the page (lesson 31.3). Each row is ROW px tall.const ROW = 80;let shown = teas;function draw() { const top = Math.max(0, -list.getBoundingClientRect().top); const first = Math.max(0, Math.floor(top / ROW) - 10); const last = Math.min(shown.length, Math.ceil((top + innerHeight) / ROW) + 10); list.style.paddingTop = `${first * ROW}px`; list.style.paddingBottom = `${(shown.length - last) * ROW}px`; list.innerHTML = shown.slice(first, last).map(row).join(""); fitNames(list.querySelectorAll(".name"));}addEventListener("scroll", draw, { passive: true });draw();- Line 2 gives every row the same height, 80 px.
styles.csssets it too. Line 3 holds the teas in their order. - Line 5 finds how far the list has scrolled up past the top of the screen.
- Lines 6 and 7 work out which rows are on screen, plus 10 above and 10 below.
- Lines 8 and 9 pad the list above and below, so it's as tall as all 5,000 rows would be.
- Line 10 puts only those rows in the page. Line 11 fits their names.
- Lines 13 and 14 draw again on every scroll, and once at the start.
Every read in draw(), on lines 5 and 7, comes before its writes. Sorting no longer moves rows:
document.querySelector("#sort-price").addEventListener("click", () => { shown = [...teas].sort((a, b) => a.cents - b.cents); draw();});Line 2 sorts the data. Line 3 draws the screenful again. The start-up's pieces from step 1 are gone too: there's no long list to fill.
A film set shows a whole street. Walk behind it, and the houses are only fronts. The crew builds what the camera sees, and moves the fronts when the camera moves.
- In real life: The street the camera sees
- In the browser: The rows near the screen
- In real life: Houses with no backs or insides
- In the browser: Teas kept as data, not as elements
- In real life: Moving the set with the camera
- In the browser: draw(), on every scroll
Sort by price fell from 1,016 ms to 56 ms. The page went from 40,020 elements to 188. Here are real frames from both versions, at the same moments after the tap:
The other tasks got faster too: every frame had less to draw, and Add no longer met start-up pieces. Pick Rendering less in the playground in Find the worst interactions to see all four.
A virtual list has a cost. The browser's find-in-page can't reach rows that aren't in the page, and lesson 31.3 listed what else needs care. The finder's own search box searches all the data, so a visitor can still find any tea. Why it matters: rendering less made every task faster at once. It's also the change that needs the most testing.
Before and after, in the field
Ravi shipped all three steps at the end of week 1. Here is worst.mjs over week 2:
p75 INP: 56 ms, from 120 visits#sort-price p75 64 ms visits 30 longest part: presentation delay (30 of 30)#compare p75 64 ms visits 29 longest part: presentation delay (29 of 29)#search p75 48 ms visits 30 longest part: presentation delay (30 of 30)#list>li.tea>button.add p75 48 ms visits 30 longest part: presentation delay (30 of 30)#list>li.tea>input.pick p75 24 ms visits 1 longest part: presentation delay (1 of 1)The p75 fell from 1,128 ms to 56 ms. On phones, it fell from 1,272 ms to 56 ms. On computers, from 280 ms to 48 ms. Every element's p75 is now under the good line. Why it matters: the p75 is the number Google rates, and it's now good on phones and computers alike.
Read each row across: the task, what the measurements said, and the step that answered it.
| Task | What did the measurements say? | What changed? | Which lessons taught it? |
|---|---|---|---|
| Add, while the list fills | Input delay: a start-up timer was adding 4,980 rows. | Step 1: add them in pieces, yielding every 50 ms. | Lessons 27.2 and 27.3. |
| Compare | Processing: the handler found similar teas before it showed anything. | Step 1: show the table, yield, then find them. | Lessons 27.2 and 28.1. |
| Typing in the search box | Processing, and keys waiting for the search before them. | Step 2: debounce, and score in a worker. | Lessons 27.4 and 28.1. |
| Sort by price | Presentation delay: 5,000 rows to restyle and lay out. | Step 3: keep only the rows near the screen. | Lessons 28.2, 31.2 and 31.3. |
One thing keeps it fast: noticing the day it gets slow again. The next project puts these checks in the build, so a slow change can't ship unseen.
Which fix for which finding?
Each finding below is one the project met. Sort it into the kind of fix that answers it:
- The longest script ran during the input delay, and a timer started it
- A tap's handler shows nothing until all its work is done
- Each key press waits for the search the key before it started
- Long work on plain data that never reads or changes the page
- Most of a tap's time comes after its handler has finished
- Most of a script's time was forced style and layout
- The page holds 40,000 elements, and the screen shows a dozen rows
Sort each finding into the kind of fix that answers it.
Common mix-ups
- "A fast handler means a fast tap." No. Add's handler ran for 24 ms, yet the tap took 1,368 ms. It waited for other work.
- "Yielding makes the work smaller." No. The start-up work still filled the main thread. Yielding only let the tap go between its pieces.
- "Each task has one longest part." No. The search's longest part was processing in 14 of its 30 field visits, presentation delay in 11, and input delay in 5. Each visitor's device changed which part was longest.
- "A worker makes the work faster." No. It moves the work off the main thread. The worker's searches were still long tasks, on its own thread.
- "Reading an element's size is always cheap." No. After a change to the page, a read makes the browser lay out again first. Read everything, then write.
- "Rendering less has no cost." No. A virtual list keeps most rows out of the page, where find-in-page can't reach them.
Practice exercises
Answer first, then use the hints. Some use the playgrounds above, one uses a published trace, and one uses the stored beacons.
These are Compare's three parts after step 1. What does line 4 print?
// Compare, after step 1, in the lab: its three parts, in ms.
const parts = { "input delay": 5, processing: 19, "presentation delay": 120 };
const [longest] = Object.entries(parts).sort((a, b) => b[1] - a[1])[0];
console.log(longest);presentation delay. After step 1, the slow scoring ran after the paint. What was left was drawing the table.
Ravi's first fallback looked like this. What happens when it runs in a browser with no scheduler, like Safari?
// Ravi's first try at a fallback.
function yieldNow() {
if (scheduler.yield) return scheduler.yield();
return new Promise((resolve) => setTimeout(resolve, 0));
}
yieldNow().then(() => console.log("yielded"));if (globalThis.scheduler?.yield) return scheduler.yield();A ReferenceError: scheduler is not defined. globalThis.scheduler?.yield checks safely: it gives undefined when scheduler is missing.
Ben types a key every 300 ms. With the finder's 250 ms debounce, how many searches run?
// Key presses, in ms, and a search 250 ms after the last key.
const keys = [0, 300, 600, 900];
const wait = 250;
let searches = 0;
keys.forEach((at, i) => {
// A search runs when no key comes within `wait` ms of this one.
if (i === keys.length - 1 || keys[i + 1] - at > wait) searches++;
});
console.log(`searches: ${searches}`);searches: 4. Each gap is longer than 250 ms, so the timer fires before the next key. Debouncing saves nothing for a slow typist, and costs nothing either.
In the playground, pick Worker. The search task's slowest interaction is no longer a key press. What kind of interaction is it?
pointer. With the keys fast, the search task's slowest interaction was the tap that put the cursor in the box. Step 3 made it fast too.
Open the trace of Compare after step 1 in DevTools' Performance panel. How many long tasks ran after the frame that showed the table?
3: one per similar-teas search, and the task that filled them in. Each ran after the frame that showed the table.
Download beacons.jsonl and queries.js. In week 1, how many visits from computers had an INP over 200 ms?
const week1 = weekOf(beacons, now, 1);
console.log(week1.filter((b) => b.device === "desktop" && b.inp?.value > 200).length);14: all 10 of the computers' Compare visits, and 4 of their Sort visits. Even a fast CPU took over 200 ms to score every tea or to move 5,000 rows.
Check your understanding
For each question, ask yourself which part of INP it's about.
Question 1 of 7The field says Add's longest part was input delay. What does the long animation frame add to that?
Choose an answer to see the explanation.
Question 2 of 7Step 1 put
await yieldNow()right after Compare draws its table. Why there?Choose an answer to see the explanation.
Question 3 of 7Why does search-worker.js have no yields in it?
Choose an answer to see the explanation.
Question 4 of 7What does this debounce program print?
Read the code, then predict// Key presses, in ms, and a search 250 ms after the last key. const keys = [0, 120, 400, 520]; const wait = 250; let searches = 0; keys.forEach((at, i) => { // A search runs when no key comes within `wait` ms of this one. if (i === keys.length - 1 || keys[i + 1] - at > wait) searches++; }); console.log(`searches: ${searches}`);Choose an answer to see the explanation.
Question 5 of 7fitNames read each name's size right after making the name before it smaller. Why was that slow?
Choose an answer to see the explanation.
Question 6 of 7What does the virtual list give up, in exchange for a much smaller page?
Choose an answer to see the explanation.
Question 7 of 7In the lab, every task was fast after step 3. Why also check the field?
Choose an answer to see the explanation.
Key takeaways
- Group your RUM's INP by element, and count which part was longest for each.
- Reproduce each one in the lab: the long animation frames name the script behind each part.
- For input delay, break up the work that was running. For a long handler, show the change, then yield.
- Move pure data work, like scoring, to a worker, and debounce work that runs on every key.
- For presentation delay, render less: read before you write, and keep only what's near the screen.
- Measure every task again after each step, then check the field's p75.
Remember the one-liner.
Let the field name the slow tap and its longest part, let the lab name the code, then yield, move, or render less.
Sources
The facts on this page come from these standards, docs and source files:
- Optimize Interaction to Next Paint, web.dev.
- web-vitals: INPAttribution (6.2.3), Google Chrome on GitHub.
- Event Timing API, W3C.
- Long Animation Frames API, W3C.
- PerformanceScriptTiming, MDN.
- Optimize long tasks, web.dev.
- Scheduler: yield() method, MDN.
- Using Web Workers, MDN.
- HTML Standard: Web workers, WHATWG.
- Avoid large, complex layouts and layout thrashing, web.dev.
- Avoid an excessive DOM size, Chrome for Developers.
- Interaction to Next Paint (INP), web.dev.
Coming next: Project: a performance pipeline. You'll make checks like these run on every change, so a slow one can't ship.