completefrontend
Open lab My progress
THE WEB PERFORMANCE FIELD GUIDE

Scrolling performance

Why a scroll can wait for JavaScript, and how passive listeners, IntersectionObserver, scroll-driven animations and sticky headers keep it smooth.

By the end, you can
  • 01
    Keep listeners from blocking the scrollKnow when a touch or wheel listener makes scrolling wait for the main thread, and make it passive.
  • 02
    Replace scroll handlersUse IntersectionObserver to learn when something enters or leaves the screen, instead of reading layout on every scroll.
  • 03
    Move 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:

Asha's phone in five real frames from Chrome, at 0 ms, 100 ms, 200 ms, 400 ms, 500 ms after her finger touched the reviews. The page had moved 0 px, 0 px, 0 px, 436.7 px, 555.4 px. Under them, one bar for every frame Chrome showed, as tall as the page had moved. Ravi's ranking code ran until 283.7 ms. The bars stay flat until then, and jump just after it.0 msAsha's phone 0 ms after her finger touched the reviews: the page has moved 0 px.moved 0 px100 msAsha's phone 100 ms after her finger touched the reviews: the page has moved 0 px.moved 0 px200 msAsha's phone 200 ms after her finger touched the reviews: the page has moved 0 px.moved 0 px400 msAsha's phone 400 ms after her finger touched the reviews: the page has moved 436.7 px.moved 436.7 px500 msAsha's phone 500 ms after her finger touched the reviews: the page has moved 555.4 px.moved 555.4 pxShaded: Ravi's ranking code, until 283.7 mstouch, 0 ms600 ms
Real frames from Chrome, and one thin bar for every frame it showed, as tall as the page had moved. For the first 300 ms, the page stayed where it was. Then it jumped to catch up with Asha's finger.

Here are the main numbers as code:

Asha's flickPop out in the code editor (opens in a new tab)JavaScript
// 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 prints The 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.

Real-life analogyA tram that must radio the control room

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
The main idea

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:

Ravi's swipe-to-hideJavaScript
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:

The same code, made passiveJavaScript
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:

Not passive or passive, calm or busyPop out in the code editor (opens in a new tab)JavaScript
// 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 ms and passive, calm: 18.2 ms.
  • Then not passive, busy: 299.9 ms and passive, 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.

The same flick during Ravi's ranking code, on two pages. With a touchstart listener without passive: in the frames up to the end of the ranking code, at 283.7 ms, the page moved in 0 of 17. With a touchstart listener with { passive: true }: in the frames up to the end of the ranking code, at 284.8 ms, the page moved in 15 of 17.Ravi's ranking codetouchstart listener without passivetouchstart listener with { passive: true }touch, 0 ms600 ms
Each thin bar is one frame Chrome showed, as tall as the page had moved. The shaded band is Ravi's ranking code. Without passive, the page waited for it. With passive, the page moved from the first frames.

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.

Playground: one flick, four ways
Ravi's swipe codeJavaScript
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;
});
Not passive, busyRecorded
The page first moved299.9 ms
All five flicks290.8 ms, 334.1 ms, 300 ms, 299.7 ms, 299.9 ms
Frames Chrome showed before that18
Ravi's listener ran at289.9 ms
event.cancelable in the listenertrue
Try it yourself
Not passive, busy: the page moved at 299.9 ms

The compositor had to wait for the main thread's answer, and the ranking code held it. The page moved only after the code ended.

Recorded in Chrome 157 with the main thread 4 times slower. Each number is the middle of 5 flicks. Times are in ms after the finger touched. "Busy" flicks came 250 ms after a tap on Helpful, while the ranking code ran.

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:

Which wheel listeners can cancel?Pop out in the code editor (opens in a new tab)JavaScript
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 wheel listener 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 is true if the cancel worked. It prints window: passive, body: passive and a 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:

Playground: scroll while the main thread is busy
The listeners on the listJavaScript
const reviews = document.querySelector("#reviews");
reviews.addEventListener("touchstart", () => {});
reviews.addEventListener("wheel", () => {});
Not passiveLive
Try it yourself
Press Run the ranking code, then scroll the reviews straight away

These listeners aren't passive, so the list should stop under your finger or wheel until the code ends.

The page below runs in this browser. One second after you press the button, its code keeps this whole tab busy for 1.5 seconds, so the lesson page freezes too. Scroll over the reviews with a finger, a wheel or a touchpad.

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:

Back to top, with a scroll listenerJavaScript
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 scroll events.
  • 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:

Back to top, with an observerJavaScript
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 isIntersecting is true: while any part of the title is on the screen.
  • Line 6 starts watching the title.
Real-life analogyWatching the door, or a doorbell

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:

One flick, two versionsPop out in the code editor (opens in a new tab)JavaScript
// 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 ms and Chrome'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.

Playground: scroll listeners and observers
This version's codeJavaScript
const title = document.querySelector("h1");
const toTop = document.querySelector(".to-top");
addEventListener("scroll", () => {
  toTop.hidden = title.getBoundingClientRect().bottom > 0;
});
Back to top: scroll listenerRecorded
Scroll events31
Scroll listener runs31
Scroll listener time7.6 ms
Observer callbacks0
Chrome's observer checks0, 0 ms
Main thread busy, in all86.9 ms
Try it yourself
Back to top: scroll listener

The listener ran in every frame of the flick, and read the title's box each time.

Recorded in Chrome 157 with the main thread 4 times slower: one flick on a calm page, in the 1000 ms after the touch. Each number is from the middle of 5 flicks.

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:

The line, moved by a scroll listenerJavaScript
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, with transform: 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:

The line, driven by the scrollCSS
.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 read at a steady speed. both keeps 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 line during the ranking codePop out in the code editor (opens in a new tab)JavaScript
// 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% and animation-timeline: scroll(): page 286.8 px, line 6.8%.
The bottom left of the header, zoomed in, in real frames on the 20-review page, at 0 ms, 100 ms, 200 ms, 300 ms, 400 ms after the touch. A scroll listener sets --read: the page had moved 0 px, 70.9 px, 189.5 px, 309.8 px, 430.1 px, and the line was 0%, 0%, 0%, 0%, 10% of the screen's width. animation-timeline: scroll(): the page had moved 0 px, 67.6 px, 186.2 px, 306.5 px, 426.8 px, and the line was 0%, 1.6%, 4.4%, 7.6%, 10.4% of the screen's width. The ranking code ended 285 ms to 290.3 ms after the touch.0 ms100 ms200 ms300 ms400 msA scroll listener sets --readThe bottom of the header 0 ms after the touch, zoomed in. The line is 0% of the screen's width.line 0%The bottom of the header 100 ms after the touch, zoomed in. The line is 0% of the screen's width.line 0%The bottom of the header 200 ms after the touch, zoomed in. The line is 0% of the screen's width.line 0%The bottom of the header 300 ms after the touch, zoomed in. The line is 0% of the screen's width.line 0%The bottom of the header 400 ms after the touch, zoomed in. The line is 10% of the screen's width.line 10%animation-timeline: scroll()The bottom of the header 0 ms after the touch, zoomed in. The line is 0% of the screen's width.line 0%The bottom of the header 100 ms after the touch, zoomed in. The line is 1.6% of the screen's width.line 1.6%The bottom of the header 200 ms after the touch, zoomed in. The line is 4.4% of the screen's width.line 4.4%The bottom of the header 300 ms after the touch, zoomed in. The line is 7.6% of the screen's width.line 7.6%The bottom of the header 400 ms after the touch, zoomed in. The line is 10.4% of the screen's width.line 10.4%
The light green stripe along the header's bottom edge is the line. The ranking code ran until about 290 ms. The listener's line stayed at 0% until then. The scroll-driven line grew with the page.

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.

Real-life analogyA speedometer on a cable

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:

Ben's photo fades inCSS
.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:

A sticky headerCSS
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:

A header moved by a scroll listenerJavaScript
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:

A fixed headerCSS
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:

The top of Asha's screen in real frames, at 0 ms, 100 ms, 200 ms, 400 ms, 500 ms after her finger touched, while the ranking code ran and just after. Moved by a scroll listener: whole header, no header, no header, 26.4 px of it, 28 px of it. position: sticky: whole header, whole header, whole header, whole header, whole header.0 ms100 ms200 ms400 ms500 msMoved by a scroll listenerThe top of Asha's screen 0 ms after the touch, with the header Moved by a scroll listener: whole header.whole headerThe top of Asha's screen 100 ms after the touch, with the header Moved by a scroll listener: no header.no headerThe top of Asha's screen 200 ms after the touch, with the header Moved by a scroll listener: no header.no headerThe top of Asha's screen 400 ms after the touch, with the header Moved by a scroll listener: 26.4 px of it.26.4 px of itThe top of Asha's screen 500 ms after the touch, with the header Moved by a scroll listener: 28 px of it.28 px of itposition: stickyThe top of Asha's screen 0 ms after the touch, with the header position: sticky: whole header.whole headerThe top of Asha's screen 100 ms after the touch, with the header position: sticky: whole header.whole headerThe top of Asha's screen 200 ms after the touch, with the header position: sticky: whole header.whole headerThe top of Asha's screen 400 ms after the touch, with the header position: sticky: whole header.whole headerThe top of Asha's screen 500 ms after the touch, with the header position: sticky: whole header.whole header
The header moved by a script slid away with the page while the ranking code ran, and came back short. The sticky header was whole in every frame.

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.

Real-life analogyA conveyor belt at a sushi bar

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?

Will it keep up?
  • The page's scroll, with a touchstart listener marked { passive: true }
  • The page's scroll, with a touchstart listener on a list and no options
  • The page's scroll, with a wheel listener on document and no options
  • A header with position: sticky; top: 0
  • A button with position: fixed
  • A reading line with animation-timeline: scroll() on transform
  • A reading line with animation-timeline: scroll() on width
  • A header moved down by a scroll listener
  • A Back to top button shown by an IntersectionObserver callback
Try it yourself
0 of 9 correct

Sort each one by what happens while the main thread is busy for 400 ms.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Then pick the tool. Read the table across: what you want, what to use, and why.

What to use instead
If you wantUseWhy
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.

Exercise 1 · Warm-upScroll events in one flick

Asha's flick lasts as long as line 1 works out. What does line 3 print?

Starter codePop out in the code editor (opens in a new tab)JavaScript
const flickMs = (600 / 1200) * 1000;
const frameMs = 1000 / 60;
console.log(`${Math.round(flickMs / frameMs)} scroll events`);

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upWhich listener can hold the scroll?

    None of these listeners passes any options. Which line's listener can make scrolling wait for the main thread?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    window.addEventListener("touchstart", track);
    document.querySelector("#reviews").addEventListener("touchstart", track);
    document.body.addEventListener("wheel", track);
    document.addEventListener("touchmove", track);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeWatching 1,000 reviews

      In the scroll listeners and observers playground, how long did Chrome's checks take for one observer watching all 1,000 reviews?

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeA line that ignores the scroll

        Ravi's line doesn't follow the scroll. What does line 4 print? Then fix line 2.

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        const line = document.createElement("div");
        line.style.cssText = "animation-timeline: scroll(); animation: read linear both;";
        document.body.append(line);
        console.log(getComputedStyle(line).animationTimeline);

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeThe box over the reviews

          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?

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeWhy preventDefault() does nothing

            Which flag on an event does the DOM spec set while a passive listener runs, so that its preventDefault() does nothing?

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask: does it wait for the main thread?

              The scrolling quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does the last line of Asha's flick example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                // 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.

              2. 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.

              3. Question 3 of 7What does the fourth line of the passive results example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                // 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.

              4. Question 4 of 7Which of these listeners is passive even though its code doesn't say so?

                Choose an answer to see the explanation.

              5. Question 5 of 7When does an IntersectionObserver with the default options call its callback?

                Choose an answer to see the explanation.

              6. 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.

              7. 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:

              Coming next: View transitions and performance. Ravi animates from one page to the next, and the same threads decide what it costs.

              CompleteFrontend Clear concepts. Working examples.