Scrolling performance
Why a scroll can wait for JavaScript, and how passive listeners, IntersectionObserver, scroll-driven animations and sticky headers keep it smooth.
- 01Keep listeners from blocking the scrollKnow when a touch or wheel listener makes scrolling wait for the main thread, and make it passive.
- 02Replace scroll handlersUse IntersectionObserver to learn when something enters or leaves the screen, instead of reading layout on every scroll.
- 03Move things with the scroll, off the main threadDrive effects with animation-timeline: scroll() and view(), and keep headers in place with position: sticky or fixed.
The page waited for Ravi's ranking code
Asha is back on Leaf and Kettle's mint tea reviews. In lesson 32.1, she tapped Helpful on Meera's review. Ravi's +1 rose, and his ranking code kept the page busy for 400 ms.
Today she taps Helpful and keeps reading. Her finger lands on the reviews and slides up the screen, to scroll down. Nothing moves. Her finger slides, and the page stays where it is. Then, all at once, the page jumps to catch up.
That's strange. Lesson 32.1 showed that the compositor keeps going while the main thread is busy. Scrolling is the compositor's job too. So why did the page wait? Here is what Asha saw, in real frames from Chrome:
Here are the main numbers as code:
// Asha's flick on Ravi's page, from Chrome's trace.// Times in ms after her finger touched the screen.const ranking = { endedAt: 283.7 };const page = { firstMovedAt: 300, firstJumpPx: 336.2 };const frames = { shownBeforeThat: 18, thatMovedThePage: 0 }; console.log(`Ravi's ranking code ended at ${ranking.endedAt} ms.`);console.log(`The page first moved at ${page.firstMovedAt} ms, by ${page.firstJumpPx} px.`);console.log(`Before that, Chrome showed ${frames.shownBeforeThat} frames. ${frames.thatMovedThePage} moved the page.`);- Lines 1 and 2 are comments. A trace is Chrome's detailed record of what it did, as in lesson 7.2. A millisecond (ms) is a thousandth of a second.
- Line 3 holds when Ravi's ranking code ended. It began before her touch, because she tapped Helpful first.
- Line 4 holds when the page first moved, and how far it moved in that one frame.
- Line 5 counts the frames Chrome showed before that. A frame is one picture on the screen.
- Line 7 prints
Ravi's ranking code ended at 283.7 ms.Line 8 printsThe page first moved at 300 ms, by 336.2 px. - Line 9 prints
Before that, Chrome showed 18 frames. 0 moved the page.
So Chrome kept showing new frames, for the swaying leaf and the rising +1. But the page didn't move in any of the 18. Then it jumped 336.2 px in one frame. Why it matters: a page that ignores a finger feels broken, even if it catches up later.
The cause is a new piece of Ravi's code. He wants Asha to hide a review by swiping it to the left. So his code listens for touches on the reviews list. Lesson 6.1 introduced the two workers involved:
- The main thread runs the page's JavaScript, and works out style, layout and paint. Ravi's ranking code and his touch listener run here.
- The compositor thread puts the page's layers together into frames. It also scrolls the page, by moving those layers.
When a finger slides, the compositor can scroll at once. But a touch listener can call preventDefault(), which cancels the scroll. So when the touch lands on an element with such a listener, the compositor has to ask first: "Will your listener cancel this?" Only the main thread can answer. During Asha's flick, it was busy with the ranking code.
A tram can leave most stops whenever the driver is ready. But at a stop with a red sign, the driver must radio the control room and wait for "go". If the control room is on another call, the tram sits there, full of people. A green sign says: just go, and tell us later.
- In real life: The tram driver
- In JavaScript: The compositor thread, which scrolls the page
- In real life: The control room
- In JavaScript: The main thread, which runs the listeners
- In real life: A stop with a red sign
- In JavaScript: An area with a listener that could cancel the scroll
- In real life: The control room on another call
- In JavaScript: Ravi's ranking code, a long task
- In real life: A green sign: go, and tell us later
- In JavaScript: A passive listener
Scrolling runs on the compositor thread, so it can follow a finger while the main thread is busy. It stops being smooth when something makes it wait for the main thread. That can be a listener that might cancel the scroll, or an effect drawn by a scroll listener.
This lesson fixes four of them: touch listeners, scroll listeners, effects that follow the scroll, and headers that stay at the top.
How the course recorded it
- The browser: Chrome 157, on a screen the size of Asha's phone, 412 by 823 px, with touch. Its CPU was slowed 4 times, as in lesson 32.1. That slows the main thread only.
- The page: Ravi's page from lesson 32.1, with 1,000 reviews, the leaf and the +1. It also has the reading line from lesson 31.4. Each version changes one thing, as the lesson says.
- The tap and the flick: a real mouse click on Meera's Helpful button. 250 ms later, Asha's finger lands on the second review and slides 600 px up the screen in half a second. A calm flick has no tap.
- How the flick was made: with DevTools'
Input.synthesizeScrollGesture. Chrome's own gesture code then sends touch events one by one, on its own timer, like a finger. Touches sent one by one through DevTools wait for a frame first, so the course didn't use them. - The numbers: five flicks of each kind, and the middle one. "Moved at" comes from Chrome's EventLatency record: the time from an input to the frame that showed it. The pictures are Chrome's screenshots of one flick near the middle. Your own times will differ.
Passive event listeners
Here is Ravi's swipe code:
const reviews = document.querySelector("#reviews");let startX = 0;reviews.addEventListener("touchstart", (event) => { startX = event.touches[0].clientX;});reviews.addEventListener("touchend", (event) => { const review = event.target.closest(".review"); if (review && startX - event.changedTouches[0].clientX > 80) review.hidden = true;});- Line 1 finds the reviews list. Line 2 keeps where the finger started.
- Lines 3 to 5 listen for
touchstart, the moment a finger touches the screen. The listener notes how far from the left it landed. - Lines 6 to 9 listen for
touchend, when the finger lifts. If it moved more than 80 px to the left, line 8 hides that review.
Nothing here cancels a scroll. But Chrome can't know that before the code runs. The DOM spec, which defines events, says so plainly: "non-passive TouchEvent listeners must block scrolling".
So Chrome marks the area where the list is drawn. When a touch starts there, the compositor sends it to the main thread, and waits for the answer before it scrolls. Chrome's source describes this case on lines 63 to 67 of main_thread_scrolling_reason.h. Scrolling "might be blocked on the main thread waiting for non-passive event handlers".
A passive listener is a promise not to call preventDefault(). You make one with the passive option:
const reviews = document.querySelector("#reviews");let startX = 0;reviews.addEventListener("touchstart", (event) => { startX = event.touches[0].clientX;}, { passive: true });reviews.addEventListener("touchend", (event) => { const review = event.target.closest(".review"); if (review && startX - event.changedTouches[0].clientX > 80) review.hidden = true;});Only line 5 changed. Now Chrome marks no area. The compositor scrolls at once, and hands the touch to the main thread to run later. The spec says the browser can then make the event uncancelable. The recording agrees. In Ravi's listener, event.cancelable was true on the first page, and false on the passive one.
The course flicked both pages, calm and busy:
// When did the page first move? ms after the touch. Middle of 5 flicks each.const flicks = [ { listener: "not passive", page: "calm", movedAt: 16.3 }, { listener: "passive", page: "calm", movedAt: 18.2 }, { listener: "not passive", page: "busy", movedAt: 299.9 }, { listener: "passive", page: "busy", movedAt: 33.8 },];for (const f of flicks) console.log(`${f.listener}, ${f.page}: ${f.movedAt} ms`);- Lines 3 to 6 hold the middle of five flicks for each page.
- Line 8 prints
not passive, calm: 16.3 msandpassive, calm: 18.2 ms. - Then
not passive, busy: 299.9 msandpassive, busy: 33.8 ms.
On the calm page, the two were within 2 ms of each other. The main thread answered at once. On the busy page, the first version waited 299.9 ms. The passive one moved at 33.8 ms, while the ranking code was still running.
Ravi's passive listener still ran late, at 293.6 ms, after the ranking code. But the scroll no longer waited for it. Why it matters: a listener that might cancel costs nothing while the main thread is free. It costs everything when it isn't. You can't know when that will be, so make touch and wheel listeners passive unless they really cancel.
const reviews = document.querySelector("#reviews");
let startX = 0;
reviews.addEventListener("touchstart", (event) => {
startX = event.touches[0].clientX;
});
reviews.addEventListener("touchend", (event) => {
const review = event.target.closest(".review");
if (review && startX - event.changedTouches[0].clientX > 80) review.hidden = true;
});299.9 ms290.8 ms, 334.1 ms, 300 ms, 299.7 ms, 299.9 ms18289.9 mstrueThe compositor had to wait for the main thread's answer, and the ranking code held it. The page moved only after the code ended.
Passive without asking
Some listeners are passive even when you don't say so. The DOM spec gives four event types a passive default: touchstart, touchmove, wheel and the old mousewheel. But only on the window, the document, the html element or the body. Ravi put his listener on the list, so it wasn't passive. You can see the rule with wheel events made in code:
const list = document.createElement("ul");
document.body.append(list);
for (const [name, target] of [["window", window], ["body", document.body], ["a list", list]]) {
target.addEventListener("wheel", (event) => event.preventDefault());
const wheel = new WheelEvent("wheel", { cancelable: true });
target.dispatchEvent(wheel);
console.log(`${name}: ${wheel.defaultPrevented ? "can stop the scroll" : "passive"}`);
}- Lines 1 and 2 add an empty list to the page.
- Line 3 takes three targets in turn: the window, the body and the list.
- Line 4 adds a
wheellistener with no options. It tries to cancel. - Lines 5 and 6 make a cancelable wheel event and send it to the target.
- Line 7 reads
defaultPrevented, which istrueif the cancel worked. It printswindow: passive,body: passiveanda list: can stop the scroll.
Chrome, Firefox and Safari all make such touch listeners passive by default. Safari doesn't do it for wheel listeners, so mark those yourself.
Finding them in DevTools
Chrome tells you when a listener held a touch back. In DevTools' Console, at the Verbose level, the recording printed this for the first page:
Handling of 'touchstart' input event was delayed for 285 ms due to main thread being busy. Consider marking event handler as 'passive' to make the page more responsive.
The Rendering tab can show these areas too. Its Scrolling performance issues option draws a box, with a label, over parts of the page whose listeners can slow scrolling down. Exercise 5 asks you what the label says.
Now try it in your own browser:
const reviews = document.querySelector("#reviews");
reviews.addEventListener("touchstart", () => {});
reviews.addEventListener("wheel", () => {});These listeners aren't passive, so the list should stop under your finger or wheel until the code ends.
IntersectionObserver instead of scroll handlers
Ravi wants a Back to top button in the bottom right corner. It should appear once the title has scrolled off the screen. His first version listens for scroll events:
const title = document.querySelector("h1");const toTop = document.querySelector(".to-top");addEventListener("scroll", () => { toTop.hidden = title.getBoundingClientRect().bottom > 0;});- Lines 1 and 2 find the title and the button.
- Line 3 listens for
scrollevents. - Line 4 reads the title's box. While its bottom edge is still below the top of the screen, the button stays hidden.
A scroll event can't be cancelled, so it never holds the scroll back. But its listener runs on the main thread, once in every frame that scrolled. The CSSOM View spec fires at most one scroll event per frame. And getBoundingClientRect() reads layout. Lesson 31.2 showed that a read after a change makes Chrome lay out at once.
An IntersectionObserver turns the question around. You don't ask where the title is in every frame. You ask Chrome to tell you when the title crosses the edge of the screen:
const title = document.querySelector("h1");const toTop = document.querySelector(".to-top");const watcher = new IntersectionObserver(([entry]) => { toTop.hidden = entry.isIntersecting;});watcher.observe(title);- Line 3 makes an observer. Chrome will call its function with a list of entries, one for each watched element that crossed. Here only the title is watched, so
[entry]takes the first. - Line 4 hides the button while
isIntersectingis true: while any part of the title is on the screen. - Line 6 starts watching the title.
Asha waits for a parcel. She could get up every minute and look out of the window. Or she can sit and read until the doorbell rings. The bell still needs power. But it only rings when something changes.
- In real life: Getting up every minute to look out
- In JavaScript: A scroll listener reading a box in every frame
- In real life: The doorbell
- In JavaScript: An IntersectionObserver
- In real life: Someone arriving at the door
- In JavaScript: The title crossing the edge of the screen
- In real life: A bell on every door in the street
- In JavaScript: Watching all 1,000 reviews
The Intersection Observer spec works like the bell. Chrome checks each watched element as part of drawing a frame. It reports one only when the answer changes, and once when watching starts. The callback then runs in a task of its own. The course timed one flick on a calm page with each version:
// Back to top, one flick on a calm page. From Chrome's trace.const listener = { calls: 31, ms: 7.615 };const observer = { calls: 1, ms: 0.027, checks: 78, checksMs: 0.977 }; console.log(`Scroll listener: ${listener.calls} calls, ${listener.ms} ms`);console.log(`Observer: ${observer.calls} call, ${observer.ms} ms`);console.log(`Chrome's checks for it: ${observer.checks}, ${observer.checksMs} ms`);- Line 2 holds the scroll listener: how often it ran, and its time in all.
- Line 3 holds the observer: its callback, and Chrome's own checks for it.
- Lines 5 to 7 print
Scroll listener: 31 calls, 7.615 ms,Observer: 1 call, 0.027 msandChrome's checks for it: 78, 0.977 ms.
The listener ran 31 times, once per frame of the flick. The observer's callback ran once, when the title left. All together, the observer cost about a millisecond. Why it matters: work that runs only when the answer changes leaves the main thread free for each frame.
Watch a few things
Ravi tried one more idea: every review fades in as it comes into view. With a scroll listener that reads all 1,000 boxes, the listener took 132.1 ms in one flick. He then tried one observer that watches all 1,000 reviews. Is that free? Pick it in the playground below. web.dev's advice is to watch only the elements you need, like the title here.
const title = document.querySelector("h1");
const toTop = document.querySelector(".to-top");
addEventListener("scroll", () => {
toTop.hidden = title.getBoundingClientRect().bottom > 0;
});31317.6 ms00, 0 ms86.9 msThe listener ran in every frame of the flick, and read the title's box each time.
Scroll-driven animations
Remember Ravi's reading line, from lessons 31.1 and 31.4? A green line under the header grows as Asha reads. A scroll listener moves it:
const header = document.querySelector("header");addEventListener("scroll", () => { const read = scrollY / (document.documentElement.scrollHeight - innerHeight); header.style.setProperty("--read", read);});- Line 2 runs the function after every scroll.
- Line 3 works out how far down Asha is, from 0 at the top to 1 at the bottom.
- Line 4 puts that in
--read. Lesson 31.4's CSS stretches the line to that width, withtransform: scaleX().
Scroll events fire on the main thread, as part of drawing a frame. So while the ranking code runs, none fire, and the line can't move. Chrome's team puts it this way: "Scrolling is performed on a separate thread and therefore delivers scroll events asynchronously."
A scroll-driven animation ties an animation to the scroll position instead of the clock. Its progress is how far the page has scrolled. Here is the line with no script at all:
.read-line { animation: read linear both; animation-timeline: scroll();}@keyframes read { from { transform: scaleX(0); } to { transform: scaleX(1); }}- Line 2 plays the keyframes named
readat a steady speed.bothkeeps the first value before it starts and the last after it ends. There's no duration: the scroll sets the length. - Line 3 is the new part.
animation-timeline: scroll()reads time from the scroll position of the nearest scrolling box: here, the page. - Lines 5 to 8 stretch the line from 0 to its full width.
Write animation-timeline after the animation shorthand. The shorthand sets every animation property, so it would reset the timeline. The spec lets scroll() take a scroller (nearest, root or self) and an axis (block, inline, x or y).
On 1,000 reviews, one flick moves the line by less than a pixel. So the course recorded both versions on a copy with 20 reviews:
// The reading line in the last frame before the ranking code ended.// From Chrome's screenshots, on a page of 20 reviews.const lines = [ { drivenBy: "a scroll listener", pageMovedPx: 290, linePercent: 0 }, { drivenBy: "animation-timeline: scroll()", pageMovedPx: 286.8, linePercent: 6.8 },];for (const l of lines) console.log(`${l.drivenBy}: page ${l.pageMovedPx} px, line ${l.linePercent}%`);- Line 4 is the listener's line. Line 5 is the scroll-driven one.
- Line 7 prints
a scroll listener: page 290 px, line 0%andanimation-timeline: scroll(): page 286.8 px, line 6.8%.
The page moved almost 300 px in both. The listener's line stayed at 0% until the ranking code ended, then jumped. The scroll-driven line kept pace with the page. Chrome ran it on the compositor: the trace reported no reason it couldn't. Inside Chrome, the compositor works out the animation's progress from its own scroll position, on lines 84 to 131 of scroll_timeline.cc.
The rules from lesson 32.1 still apply. Animate transform or opacity. A scroll-driven animation of width would still need layout in every frame.
In an old car, a cable runs from the wheels to the speedometer. When the wheels turn, the needle moves. Nobody has to do anything. Now picture a passenger who reads the speed and writes it on a card instead. When she takes a phone call, the card stops changing.
- In real life: The wheels turning
- In JavaScript: The page scrolling
- In real life: The cable from the wheels to the needle
- In JavaScript: animation-timeline: scroll()
- In real life: A passenger writing the speed on a card
- In JavaScript: A scroll listener setting --read
- In real life: The passenger on the phone
- In JavaScript: Ravi's ranking code
view(): one element's trip across the screen
scroll() follows the whole scroll. view() follows one element as it crosses the screen. Here, Ben's photo fades in as it arrives:
.photo { animation: appear linear both; animation-timeline: view(); animation-range: entry;}@keyframes appear { from { opacity: 0; transform: scale(0.9); }}- Line 3 uses the photo's own trip across the screen as the timeline.
- Line 4 plays the animation only during
entry: from the moment the photo's top edge appears until all of it is on screen. - Line 7 starts it see-through and a little smaller. With no end keyframe, it ends at the photo's own style.
Sticky and fixed elements
Ravi's header stays at the top of the screen. Since lesson 31.1, it has done that with one CSS rule:
header { position: sticky; top: 0; }The spec describes sticky like this: "Same as relative, except the offsets are calculated automatically to keep the element in view as the user scrolls." top: 0 says where to keep it: at the top edge.
Without sticky, a script has to move the header down as the page scrolls. The course tried that too:
const bar = document.querySelector("header");addEventListener("scroll", () => { bar.style.transform = `translateY(${scrollY}px)`;});This header has position: absolute, so it sits at the top of the page, not the screen. On every scroll, line 3 moves it down by scrollY, the distance scrolled. A third version uses position: fixed, which keeps an element in one place on the screen:
header { position: fixed; top: 0; left: 0; right: 0; }
body { padding-top: 48px; }Line 1 fixes the header to the top of the screen. A fixed box "does not move when the document is scrolled". Line 2 gives the page room, since the header no longer takes up space. Here are the scripted header and the sticky one during the same flick:
While the ranking code ran, no scroll event fired. The scripted header scrolled away with the page: from 87 ms to 337 ms, none of it was on screen. Then it came back, but short. In each frame until the flick ended, about 20 px of it were missing. That's how far the page moved in one frame. A scroll listener always works from where the compositor was a frame ago.
The sticky and fixed headers were whole in every frame. Chrome hands the sticky rule to the compositor, which works out the offset each time it moves a layer. A fixed element isn't attached to the page's scroll at all. Why it matters: for anything that should stay or stick, use position: sticky or fixed, never a scroll listener.
At a sushi bar, plates ride a belt past you. The menu stuck to the counter never moves. Another menu rides the belt until a little stopper holds it in front of you. But if the chef has to carry a menu back after every turn, it drifts away whenever he's busy cooking.
- In real life: The belt and its plates
- In JavaScript: The page and its reviews, scrolling
- In real life: The menu stuck to the counter
- In JavaScript: position: fixed
- In real life: A menu that rides the belt until it hits a stopper
- In JavaScript: position: sticky; top: 0
- In real life: The chef carrying the menu back
- In JavaScript: A scroll listener moving the header
Will it keep up with Asha's finger?
For each one, ask: does the compositor handle it, or does it need the main thread?
- The page's scroll, with a
touchstartlistener marked{ passive: true } - The page's scroll, with a
touchstartlistener on a list and no options - The page's scroll, with a
wheellistener ondocumentand no options - A header with
position: sticky; top: 0 - A button with
position: fixed - A reading line with
animation-timeline: scroll()ontransform - A reading line with
animation-timeline: scroll()onwidth - A header moved down by a
scrolllistener - A Back to top button shown by an
IntersectionObservercallback
Sort each one by what happens while the main thread is busy for 400 ms.
Then pick the tool. Read the table across: what you want, what to use, and why.
| If you want | Use | Why |
|---|---|---|
| To run code when a touch or wheel starts. | A passive listener. | The compositor scrolls at once, and runs your code later. |
| To stop the scroll in one small area, like a map. | A listener that isn't passive, on that area only. | Only touches there wait for the main thread. |
| To know when something enters or leaves the screen. | An IntersectionObserver. | Its callback runs only when the answer changes. |
| To move or fade something with the scroll. | animation-timeline: scroll() or view(). | The compositor drives it from its own scroll position. |
| To keep a header or button in place. | position: sticky or fixed. | The compositor keeps it there in every frame. |
Common mix-ups
- "A touch listener only costs what its code costs." No. Ravi's listener took well under a millisecond, but the page waited 299.9 ms for the main thread.
- "passive: true makes the listener run sooner." No. It ran after the ranking code on both pages. Only the scroll stopped waiting for it.
- "Every listener on the window can cancel the scroll." No. Touch and wheel listeners on the window, document, html or body are passive by default.
- "Scroll listeners are fine once the page is fast." No. Even after the ranking code, the scripted header was about 20 px short in every frame.
- "An IntersectionObserver is free." No. Chrome checks every watched element in every frame. Watch the few you need.
- "A scroll-driven animation is always smooth." No. It follows lesson 32.1's rules: transform and opacity can run on the compositor, width can't.
Practice exercises
Answer first, then use the hints.
Asha's flick lasts as long as line 1 works out. What does line 3 print?
const flickMs = (600 / 1200) * 1000;
const frameMs = 1000 / 60;
console.log(`${Math.round(flickMs / frameMs)} scroll events`);30 scroll events: one per frame, at most. The recording counted 31, because a flick doesn't start or stop exactly on a frame. Each one ran Ravi's scroll listener.
None of these listeners passes any options. Which line's listener can make scrolling wait for the main thread?
window.addEventListener("touchstart", track);
document.querySelector("#reviews").addEventListener("touchstart", track);
document.body.addEventListener("wheel", track);
document.addEventListener("touchmove", track);Line 2. The reviews list is an ordinary element, so its touchstart listener isn't passive. The other three are passive by default, so they can't cancel.
In the scroll listeners and observers playground, how long did Chrome's checks take for one observer watching all 1,000 reviews?
91.8 ms. Less than the scroll listener's 132.1 ms, but far from free: Chrome checked all 1,000 watched reviews in every frame. Watch the few elements you need.
Ravi's line doesn't follow the scroll. What does line 4 print? Then fix line 2.
const line = document.createElement("div");
line.style.cssText = "animation-timeline: scroll(); animation: read linear both;";
document.body.append(line);
console.log(getComputedStyle(line).animationTimeline);line.style.cssText = "animation: read linear both; animation-timeline: scroll();";auto: the clock-based timeline every animation uses by default. The shorthand came second, and reset the timeline. Put animation-timeline after it.
Open the course's copy of Ravi's first page, and then his passive one. With Scrolling performance issues on, what label does Chrome draw over the first page's reviews?
touch event listener: NONE. NONE is the touch action Chrome gives an area inside a listener that isn't passive: the compositor may do nothing there until the main thread answers. The passive page has no box.
Which flag on an event does the DOM spec set while a passive listener runs, so that its preventDefault() does nothing?
The in passive listener flag. While a passive listener runs, the event has it set, and setting the canceled flag does nothing. So preventDefault() is ignored.
Check your understanding
For each question, ask: does it wait for the main thread?
Question 1 of 7What does the last line of Asha's flick example print?
Read the code, then predict// Asha's flick on Ravi's page, from Chrome's trace. // Times in ms after her finger touched the screen. const ranking = { endedAt: 283.7 }; const page = { firstMovedAt: 300, firstJumpPx: 336.2 }; const frames = { shownBeforeThat: 18, thatMovedThePage: 0 }; console.log(`Ravi's ranking code ended at ${ranking.endedAt} ms.`); console.log(`The page first moved at ${page.firstMovedAt} ms, by ${page.firstJumpPx} px.`); console.log(`Before that, Chrome showed ${frames.shownBeforeThat} frames. ${frames.thatMovedThePage} moved the page.`);Choose an answer to see the explanation.
Question 2 of 7Scrolling runs on the compositor thread. Why did Ravi's first page still wait for his ranking code?
Choose an answer to see the explanation.
Question 3 of 7What does the fourth line of the passive results example print?
Read the code, then predict// When did the page first move? ms after the touch. Middle of 5 flicks each. const flicks = [ { listener: "not passive", page: "calm", movedAt: 16.3 }, { listener: "passive", page: "calm", movedAt: 18.2 }, { listener: "not passive", page: "busy", movedAt: 299.9 }, { listener: "passive", page: "busy", movedAt: 33.8 }, ]; for (const f of flicks) console.log(`${f.listener}, ${f.page}: ${f.movedAt} ms`);Choose an answer to see the explanation.
Question 4 of 7Which of these listeners is passive even though its code doesn't say so?
Choose an answer to see the explanation.
Question 5 of 7When does an IntersectionObserver with the default options call its callback?
Choose an answer to see the explanation.
Question 6 of 7While the ranking code ran, why did the line with animation-timeline: scroll() keep growing?
Choose an answer to see the explanation.
Question 7 of 7After the ranking code ended, the header moved by a scroll listener was still about 20 px short in each frame. Why?
Choose an answer to see the explanation.
Key takeaways
- Scrolling runs on the compositor thread, so it can follow a finger while the main thread is busy.
- A touch or wheel listener that isn't passive makes the compositor wait for the main thread. Make it passive unless it must cancel.
- Touch and wheel listeners on the window, document, html or body are passive by default. On any other element they aren't.
- Scroll listeners run on the main thread in every frame. Use an IntersectionObserver to learn when something enters or leaves the screen.
- animation-timeline: scroll() and view() tie an animation to the scroll. With transform or opacity, the compositor runs it.
- position: sticky and fixed are kept in place by the compositor. A header moved by a scroll listener lags and drifts.
Remember the one-liner.
Let the compositor scroll on its own: passive listeners, observers, scroll-driven animations and sticky positions.
Sources
The facts on this page come from these specs, docs and source files:
- thread_cpu_throttler.cc: CPU throttling slows the page's main thread, Chromium source.
- input_handler.cc: touches and wheel events sent one by one wait for a frame; synthesizeScrollGesture doesn't, Chromium source.
- synthetic_gesture_controller.cc: a gesture's events on their own timer, and the first gesture's wait, Chromium source.
- event_latency_tracing_recorder.cc: EventLatency, from the input to the frame that showed it, Chromium source.
- DOM Standard: observing event listeners, WHATWG.
- main_thread_scrolling_reason.h: scrolling blocked by non-passive wheel and touch handlers, Chromium source.
- input_handler_proxy.cc: the compositor's hit test for touch listeners, Chromium source.
- Improving scroll performance with passive event listeners, Chrome for Developers.
- DOM Standard: the default passive value, WHATWG.
- event_target.cc: passive by default, and the blocked-event warning, Chromium source.
- event.cc: preventDefault() inside a passive listener, Chromium source.
- Discover issues with rendering performance: Scrolling performance issues, Chrome for Developers.
- heads_up_display_layer_impl.cc: the labels on the scrolling overlay, Chromium source.
- layout_object.h: the touch action inside a blocking touch listener, Chromium source.
- CSSOM View: scrolling events, W3C.
- HTML: update the rendering, WHATWG.
- Intersection Observer, W3C.
- IntersectionObserver's coming into view, web.dev.
- Scroll-driven Animations, W3C.
- CSS Animations Level 2: the animation-timeline property, W3C.
- Animate elements on scroll with scroll-driven animations, Chrome for Developers.
- A case study on scroll-driven animations performance, Chrome for Developers.
- animation.cc: a scroll timeline's source must be composited, Chromium source.
- scroll_timeline.cc: the compositor's scroll timeline reads its own scroll position, Chromium source.
- CSS Positioned Layout Level 3: sticky and fixed positioning, W3C.
- paint_property_tree_builder.cc: sticky rules handed to the compositor, Chromium source.
- paint_property_tree_builder.cc: fixed elements left out of the page's scroll, Chromium source.
- property_tree.cc: the compositor works out the sticky offset, Chromium source.
Coming next: View transitions and performance. Ravi animates from one page to the next, and the same threads decide what it costs.