Debugging CLS
Find which element moved and why: read CLS attribution from real visits, the Layout shifts track in DevTools, and jumps while scrolling and in SPAs.
- 01Read a CLS report from the fieldSend web-vitals' attribution with each visit's CLS, and read what moved, when, and how far the page had loaded.
- 02Watch the jump in DevToolsMake the jump happen in the lab, find it on the Layout shifts track, and read its sources to find what made room.
- 03Catch jumps after the loadFind jumps that come while visitors scroll, or as they move between the pages of a single-page app.
A jump that came after the load
In lesson 30.3, Ravi fixed every jump on his mint tea page. His test loads the page in Chrome. Its CLS is now 0. CLS, Cumulative Layout Shift, is Chrome's score for how much a page jumps.
Then Ravi adds his customers' reviews under Add to cart. Ben's review has a photo of his glass of tea.
Asha opens the page on her phone. She reads the brewing steps, then scrolls down to the reviews. She stops at Ben's review. A moment later, the review under it drops down her screen.
Ravi's page sends him its CLS after every visit, as in lesson 30.1. Here are two loads of the same page: his test, and Asha's visit.
// Two loads of the same page, recorded in Chromeconst loads = [ { who: "Ravi's test", scrolled: "no", cls: 0 }, { who: "Asha's visit", scrolled: "yes", cls: 0.1486 },];for (const load of loads) { console.log(`${load.who}: scrolled ${load.scrolled}, CLS ${load.cls}`);}- Line 1 is a comment. The course loaded the page both ways in Chrome.
- Lines 3 and 4 hold the two loads. Ravi's test loads the page and waits. Asha scrolls, like a real reader.
- Lines 6 to 8 print one line per load:
Ravi's test: scrolled no, CLS 0andAsha's visit: scrolled yes, CLS 0.1486.
0.1486 is over 0.1, so it "needs improvement". Ravi has two questions. Which element moved, and what made it move? And why didn't his own test see it? Here is Asha's screen just before the jump, and just after it:
Ben's photo came in with no size, and everything under it moved down. That's the answer. But Ravi doesn't know it yet. All he has is a number. This lesson follows him from the number to the photo.
A customer leaves a card at the Leaf and Kettle: "My cup slid off table 5 at 2:15." The card says where and when. It doesn't say why. So Meera sets table 5 the same way and watches at 2:15. A waiter squeezes a new chair in beside it, and the table moves.
- In real life: The customer's card
- In JavaScript: A report from a real visit: the field data
- In real life: "Table 5"
- In JavaScript: What moved:
largestShiftTarget - In real life: "At 2:15"
- In JavaScript: When:
largestShiftTime - In real life: Setting table 5 again and watching
- In JavaScript: Making the jump happen in the lab, in a DevTools trace
- In real life: The new chair squeezed in beside it
- In JavaScript: What made room: just above what moved
Debugging CLS means answering two questions: what moved, and what made room for it? Every layout shift lists what moved. A report from a real visit tells you where and when. A trace lets you watch it happen. Then you look just above what moved.
The rest of the lesson takes those steps in turn:
- Read the field report: what moved, when, and how far the page had loaded.
- Make the jump happen in the lab, and watch it on the Layout shifts track.
- Read the shift's sources, and look just above them.
- Look for the jumps that come late: while scrolling, and in single-page apps.
How the course recorded it
- The browser: Chrome 157, on a screen the size of Asha's phone: 412 px wide and 823 px tall.
- The network: the course's own server held some files back, the way a slow phone network would. Lesson 30.2's page had the same holds as before. Ben's photo waited 1.5 seconds.
- The reports: each page ran the web-vitals library, version 6.2.3. It sent CLS to the course's server when the page was hidden. Asha "left" each page by going to another one.
- Scrolling and clicking: the course turned the mouse wheel and clicked the mouse through DevTools' protocol. The protocol passes each turn of the wheel on at the next frame. So the lesson times each turn by when the page really scrolled.
Reading the field report
Ravi starts with the clue he has: the report from Asha's visit. A number alone can't tell him what to fix. So his page uses web-vitals' attribution build, from lesson 12.1. It adds an object called attribution to each report: notes on what moved. Here is how his page sends it:
// The page loads web-vitals' attribution build first, as webVitals.webVitals.onCLS((metric) => { const { largestShiftTarget, largestShiftTime, loadState } = metric.attribution; const report = { cls: metric.value, id: metric.id, largestShiftTarget, largestShiftTime, loadState }; navigator.sendBeacon("/cls", JSON.stringify(report));});- Line 1 is a comment. The attribution build gives the page an object called
webVitals. - Line 2 asks for CLS. web-vitals calls the function when the page is hidden: when Asha switches tabs, closes it, or goes to another page.
- Line 3 takes three notes out of the attribution. Line 4 puts them in a report, with the CLS and the report's
id. - Line 5 sends it with
sendBeacon. That still gets out as the page closes, as lesson 12.3 showed.
The notes are about one layout shift: the biggest one in the burst that became the page's CLS. Lesson 30.1 called that burst a session window. The attribution has six fields:
largestShiftTarget: the first element in that shift's list of what moved. It's written as a CSS selector, a short text that points at an element, like#review-15.largestShiftTime: when the shift happened, in milliseconds (ms) from the start of the page load.largestShiftValue: that one shift's score.loadState: how far the page had loaded at that moment.largestShiftSourceandlargestShiftEntry: the browser's own records of that element and that shift, for when you need more.
Here is the report Ravi's server got from Asha:
// The report Ravi's server got when Asha left the pageconst report = { cls: 0.1486, largestShiftTarget: "#review-15", largestShiftTime: 4910.5, largestShiftValue: 0.1486, loadState: "complete" };const share = report.largestShiftValue / report.cls; console.log(`The biggest jump moved ${report.largestShiftTarget} at ${report.largestShiftTime} ms.`);console.log(`It was ${Math.round(share * 100)}% of the CLS.`);console.log(`Load state: ${report.loadState}`);- Line 2 holds the report, as the server got it.
- Line 3 works out the biggest shift's share of the CLS.
- Lines 5 to 7 print
The biggest jump moved #review-15 at 4910.5 ms.,It was 100% of the CLS.andLoad state: complete.
One jump made all of Asha's CLS. It moved #review-15: Ana's review, the one under Ben's. web-vitals names an element by walking up the page to the first element with an id. This review has its own id, so the name is short.
During the load, or after it?
loadState has four values. web-vitals picks one by comparing the shift's time with the page's own milestones, from lesson 5.1:
loading: the browser was still reading the HTML.dom-interactive: the HTML was read, but DOMContentLoaded hadn't started.dom-content-loaded: DOMContentLoaded had started, but images and other files were still coming.complete: the page had finished loading.
Ravi puts Asha's report next to one from lesson 30.2's page:
// The biggest jump in two reports, and how far each page had loadedconst reports = [ { page: "Lesson 30.2's page", target: "#steps", time: 713.6, loadState: "dom-content-loaded" }, { page: "Asha's visit", target: "#review-15", time: 4910.5, loadState: "complete" },];for (const r of reports) { const when = r.loadState === "complete" ? "after the load" : "during the load"; console.log(`${r.page}: ${r.target} at ${r.time} ms, ${when}`);}- Lines 2 to 5 hold the biggest jump from each report.
- Line 7 turns the load state into words. Line 8 prints one line per report.
- It prints
Lesson 30.2's page: #steps at 713.6 ms, during the loadandAsha's visit: #review-15 at 4910.5 ms, after the load.
Asha's page had finished loading at 2,528.5 ms. Her jump came about 2.4 seconds later. Why it matters: a jump during the load shows up when you reload the page in a test. A jump after it only shows up if you use the page, the way the visitor did.
One visit can send more than one report
web-vitals calls back each time the page is hidden, not once per visit. And Chrome may keep a page you left in its back/forward cache, ready for the Back button. The course left lesson 30.2's page, pressed Back, and left again:
// Two reports from one tab: Asha leaves, presses Back, and leaves againconst reports = [ { cls: 0.2546, navigationType: "navigate", id: "v6-1794569594998-2377225040134" }, { cls: 0, navigationType: "back-forward-cache", id: "v6-1794569599802-6272119206044" },];for (const r of reports) console.log(`${r.navigationType}: CLS ${r.cls}`);console.log(`The same id? ${reports[0].id === reports[1].id}`);- Lines 2 to 5 hold the two reports the server got.
- Line 6 prints
navigate: CLS 0.2546andback-forward-cache: CLS 0. - Line 7 prints
The same id? false.
Chrome restored the page just as Asha had left it, with nothing left to load. So nothing moved. web-vitals treats the restored page as a new visit, with a new id and a CLS that starts at 0. Why it matters: count reports by their id, and read navigationType before you blame a page.
Here are the real reports. Pick one to see every field the server got:
/story/0.2546poornavigate4,254.4 ms, page hidden#steps713.6 ms0.1829dom-content-loadedChrome loaded lesson 30.2's page, and Asha left. The biggest jump was the photo's, during the load.
Watching it on the Layout shifts track
A report is a clue, not an answer. web.dev puts it plainly: "You can't fix layout shifts that you can't reproduce." To reproduce a jump is to make it happen again, where you can watch it.
Ravi starts with a jump he knows: lesson 30.2's page, before its fixes. Its jumps all came during the load. So he opens DevTools' Performance panel, from lesson 7.1, and records a reload. DevTools draws the recording as a trace, in rows called tracks. One row is the Layout shifts track.
On it, each layout shift is a purple diamond. A bigger diamond means a bigger score. Shifts close together sit on one purple line, called a cluster. Hover over a diamond, and DevTools highlights what moved on the page. Click it, and the Summary below shows its time, its score, the elements that moved, and possible culprits.
Ravi's shop has a doorbell camera. Its app shows the day as a line. Each time something moves at the door, it adds a mark there. A big movement gets a big mark. Movements close together make one clip. Tap a mark, and the app plays what moved.
- In real life: A mark on the day's line
- In JavaScript: A diamond: one layout shift
- In real life: A big mark for a big movement
- In JavaScript: A big diamond for a high score
- In real life: Marks close together, in one clip
- In JavaScript: A cluster: shifts less than a second apart
- In real life: Tapping a mark to watch it
- In JavaScript: Clicking a diamond: the Summary, and a replay of the shift
Behind the panel, the trace holds Chrome's own record of each shift: a LayoutShift event. Here are the events from the course's trace:
// Chrome's LayoutShift events in the trace of lesson 30.2's pageconst shifts = [ { ms: 713.6, score: 0.18289, frame: "page" }, { ms: 1341, score: 0.01378, frame: "page" }, { ms: 1920.4, score: 0.05795, frame: "page" }, { ms: 2533.9, score: 0.04667, frame: "ad" },];const cluster = shifts.reduce((sum, shift) => sum + shift.score, 0);console.log(`The biggest diamond: ${Math.max(...shifts.map((shift) => shift.score))}`);console.log(`The cluster: ${cluster.toFixed(4)}`);- Lines 3 to 6 hold the four events: when, their score, and which document they were in.
- Line 6 was inside the ad's iframe. Its score is scaled to the ad's share of the screen, as lesson 30.2 showed.
- Line 8 adds the scores up. Line 9 prints
The biggest diamond: 0.18289, the photo's jump. Line 10 printsThe cluster: 0.3013.
The four shifts came less than a second apart, so DevTools drew one cluster. Its score is Chrome's own CLS for the page, from lesson 30.2. DevTools' source shows how it builds clusters:
- It uses CLS's session window rules. A gap of a second ends a cluster, and none runs past 5 seconds.
- A cluster also ends at a navigation, when a new page starts.
- It leaves out shifts right after a click, tap or key press. CLS skips those too.
- It counts shifts inside iframes, scaled down, like Chrome's own CLS.
Now Asha's jump. Her report said complete, so a reload won't show it. Ravi's test loaded the page and waited, and nothing moved. So Ravi records the way Asha used the page. He presses Record, scrolls down to Ben's review, waits, and stops. Here are both recordings, on one time scale:
In the reload, the diamonds sit inside the load. In Asha's recording, the page finished loading at 2,528.5 ms, and the one diamond came at 4,910.4 ms. Why it matters: for a jump after the load, record while you use the page, not while you reload it.
The Insights tab has a check for this, Layout shift culprits, from lesson 7.3. It guesses a cause for the worst cluster. For Asha's recording, it named an image with no size: ben.jpg. For lesson 30.2's page, it named three: the photo, a web font, and the ad's own photo. Lesson 7.3 showed it can guess wrong, so check its guess against the sources.
Pick a recording to see each diamond and cluster, as DevTools' own code read them:
0.18289: ol#steps, section#reviews, button#add0.01378: section#reviews, button#add, li, li, li0.05795: section#reviews, button#add0.04667: p#ad-text0.3013, 4 shiftsan image with no size: mint-tea.jpg; a web font; an image with no size: chamomile.jpgA reload recording: Chrome loaded lesson 30.2's page, and nobody touched it.
What a shift's sources tell you
A diamond tells Ravi when the page jumped. Its list of elements tells him what moved. In JavaScript, that list is the layout-shift entry's sources, from lesson 11.3. The Layout Instability spec sets its rules:
- It lists up to five things that moved: elements, or runs of text.
- The one that covered the most screen comes first. Chrome's own code sorts them that way.
- Each source has a
node: the element itself. And it has two boxes.previousRectis where the element was in the frame before.currentRectis where it is now.
The boxes are in CSS pixels, measured from the top-left corner of the screen, like getBoundingClientRect(). They only count the part of the element that's on the screen.
When the café closes, Meera draws a chalk line around each chair. In the morning, she draws them again. Where the lines don't match, a chair moved, and the gap shows how far. A chair with no morning line has left the room. All the moved chairs start near one corner. That's where someone put a new table.
- In real life: The evening's chalk line
- In JavaScript:
previousRect: the box in the frame before - In real life: The morning's chalk line
- In JavaScript:
currentRect: the box now - In real life: The gap between the two lines
- In JavaScript: How far the element moved
- In real life: A chair with no morning line
- In JavaScript: A
currentRectof all zeros: pushed off the screen - In real life: The new table in the corner
- In JavaScript: What made room: just above the first source
Here are the sources of Asha's jump, as Chrome wrote them:
// The sources of Asha's jump: where each one was, and where it wentconst sources = [ { node: "#review-15", previousRect: { y: 323.59, height: 128 }, currentRect: { y: 558.33, height: 128 } }, { node: "#review-17", previousRect: { y: 555.59, height: 128 }, currentRect: { y: 790.33, height: 32.67 } }, { node: "#review-16", previousRect: { y: 463.59, height: 80 }, currentRect: { y: 698.33, height: 80 } }, { node: "#review-18", previousRect: { y: 695.59, height: 127.41 }, currentRect: { y: 0, height: 0 } },];for (const { node, previousRect, currentRect } of sources) { if (currentRect.height === 0) console.log(`${node}: pushed off the screen`); else console.log(`${node}: down ${(currentRect.y - previousRect.y).toFixed(1)} px`);}- Lines 3 to 6 hold the four sources, in Chrome's order: the biggest first.
- Line 9 checks for a box with nothing left on the screen. Line 10 subtracts the old top from the new one.
- It prints
#review-15: down 234.7 px,#review-17: down 234.7 pxand#review-16: down 234.7 px. Last comes#review-18: pushed off the screen.
Three things stand out:
- Everything moved the same distance, down. web.dev says "a large downward shift often indicates the insertion of a DOM element". Something new took 234.7 px of room.
#review-18's new box is all zeros. It was pushed below the bottom of the screen. All zeros in the old box means the opposite: the element came into view.- Nothing above Ana's review moved. So the room was made just above it.
Lesson 30.2 showed that the sources name what moved, not what made room. web.dev's advice is to look at "the DOM element immediately preceding the shifted element". In code, that's previousElementSibling:
new PerformanceObserver((list) => { for (const shift of list.getEntries()) { const moved = shift.sources[0]?.node; const above = moved?.previousElementSibling; console.log("Moved:", moved, "Just above it:", above); }}).observe({ type: "layout-shift", buffered: true });- Line 1 watches for layout shifts, as in lesson 11.3.
- Line 3 takes the first source's node: the one that covered the most screen.
- Line 4 takes the element just before it on the page. Line 5 logs both.
On Asha's page, the first source was #review-15. The element just before it is #review-14: Ben's review. Inside it is his photo, with no width or height. At 352 px wide, that photo is 234.7 px tall. Why it matters: the sources point at the spot, and looking just above finds the cause.
web-vitals reads the same list. Its largestShiftSource is the first source that's an element, not a run of text. largestShiftTarget is that element's selector. So Asha's report named the review that covered the most screen.
Try it in your own browser. Each change happens a little after your click, so the click doesn't excuse it:
setTimeout(change, 700);new PerformanceObserver((list) => { for (const shift of list.getEntries()) for (const { node, previousRect, currentRect } of shift.sources) show(node, previousRect.y, currentRect.y);}).observe({ type: "layout-shift" });pick a changePick a change. It happens 700 ms after your click, so your click doesn't excuse it.
Jumps while you scroll
So why did Ravi's test miss Ben's photo? Here is the photo in the page:
<article class="review" id="review-14"> <div class="card"><h3>Ben</h3><p>Strong mint, and it stays bright even with honey in it.</p> <img class="shot" src="ben.jpg" loading="lazy" alt="Ben's glass of mint tea"> </div></article>Line 3 is the photo. loading="lazy" tells Chrome to wait until the reader scrolls near it. It has no width and no height.
Lesson 18.3 showed that on a fast connection, Chrome asks for a lazy image once it's within 1,250 px of the screen. Ben's photo sat 2,692.6 px down the page. Ravi's test never scrolled, so Chrome never asked for the photo. The test's list of files has no ben.jpg at all.
Asha did scroll. Here is her scroll, from the recording:
// Asha's scroll, from the recording, in msconst lastTurn = 4606.8; // her last turn of the wheel scrolled the pageconst asked = 3407; // Chrome asked for Ben's photoconst arrived = 4909.8; // the photo arrivedconst jump = 4910.5; // the layout shiftconsole.log(`The photo took ${(arrived - asked).toFixed(1)} ms to come.`);console.log(`The jump came ${(jump - lastTurn).toFixed(1)} ms after she stopped.`);- Lines 2 to 5 hold four times from the recording.
- Line 6 prints
The photo took 1502.8 ms to come. - Line 7 prints
The jump came 303.7 ms after she stopped.
Chrome asked for the photo right after Asha's second turn of the wheel. While it was on its way, she kept scrolling. She stopped with the photo's spot 297.6 px from the top of her screen. It was 0 px tall. Then the photo arrived, and everything under it moved.
Scrolling doesn't excuse a jump. The spec says a scroll isn't input. The entry's lastInputTime was 0, so hadRecentInput was false, and the jump counted in full. web.dev names this exact case: "CLS often happens while the user scrolls through a page, when lazy-loaded content loads fully without space reserved for it." Why it matters: the fix is lesson 30.3's. Give the photo its width and height.
Scroll anchoring keeps your place
Meera has an idea: show new reviews at the top of the list as they come in. Ravi worries. Asha reads further down. Won't every new review push her page? He tests it. Once Asha has stopped at Ben's review, a script adds one review at the top of the list:
setTimeout(() => { document.querySelector("#more h2").insertAdjacentHTML("afterend", '<article class="review" id="review-new"><div class="card"><h3>Kofi</h3><p>Just tried it after dinner. Cool and fresh, and not too strong.</p></div></article>'); performance.mark("new-review");}, 5600 - performance.now());- Line 1 sets a timer. Line 4 says when it fires: 5,600 ms after the page started.
- Line 2 adds Kofi's review right after the list's heading, far above Asha's screen.
- Line 3 notes the moment, for the recording.
Then he loads the page again, with one line of CSS that turns scroll anchoring off:
body { overflow-anchor: none; }Here is what Chrome did each time:
// The same new review, with scroll anchoring on and offconst loads = [ { anchoring: "on", scrollBefore: 2395, scrollAfter: 2511, cls: 0 }, { anchoring: "off", scrollBefore: 2395, scrollAfter: 2395, cls: 0.1281 },];for (const load of loads) { const scrolled = load.scrollAfter - load.scrollBefore; console.log(`Anchoring ${load.anchoring}: Chrome scrolled ${scrolled} px, CLS ${load.cls}`);}- Lines 3 and 4 hold each load: where the page was scrolled before and after, and its CLS.
- It prints
Anchoring on: Chrome scrolled 116 px, CLS 0andAnchoring off: Chrome scrolled 0 px, CLS 0.1281.
With the usual CSS, Chrome scrolled the page down 116 px by itself. That's exactly the new review's height, with its gap. So nothing on Asha's screen moved, and there was no layout shift. With anchoring off, everything on her screen moved down 116 px. One source, #review-11, had an old box of all zeros: it slid into view from above.
Asha reads a binder of recipes, with a finger on her line. Meera slips new recipes in at the front. The pages before Asha's finger get thicker. Her finger moves with her page, so she never loses her place. But if a page goes in below her finger, the lines under it still move away.
- In real life: Asha's finger
- In JavaScript: The anchor: an element near the top of the screen
- In real life: New pages slipped in at the front
- In JavaScript: Content added above the anchor
- In real life: The finger moving with her page
- In JavaScript: Chrome scrolling by the same amount
- In real life: A page slipped in below her finger
- In JavaScript: Content added below the anchor: it still moves things
- In real life: Reading with no finger
- In JavaScript:
overflow-anchor: none
That's scroll anchoring. The CSS Scroll Anchoring spec says it works by "adjusting the scroll position to compensate for the changes outside the viewport." Here are its rules:
- The browser picks an anchor: an element near the top of the screen.
- When the anchor moves because something above it grew, the browser scrolls by the same amount.
- A change below the anchor doesn't move it, so nothing is fixed. Ben's photo grew below the anchor, on the screen. That's why its jump counted.
- No anchor is picked if the page isn't scrolled at all. Then a change at the top still pushes everything.
overflow-anchor: noneturns it off for an element and everything inside it.
Why it matters: scroll anchoring hides changes above the screen, for free, so don't turn it off without a reason. It can't hide a change on the screen itself. Try it in a box of reviews:
box.style.overflowAnchor = mode; // "auto" or "none"setTimeout(() => { box.querySelector("ol").prepend(newReview);}, 700);- Asha Fresh mint, cool and sweet.
- Ravi Fresh mint, cool and sweet.
- Meera Fresh mint, cool and sweet.
- Ben Fresh mint, cool and sweet.
- Ana Fresh mint, cool and sweet.
- Sam Fresh mint, cool and sweet.
- Priya Fresh mint, cool and sweet.
- Leo Fresh mint, cool and sweet.
- Kofi Fresh mint, cool and sweet.
- Mia Fresh mint, cool and sweet.
press Addpress AddnoneScroll the box down a little, then press Add. Try it with each setting, and once without scrolling at all.
Jumps in a single-page app
Ravi has rebuilt his tea list as a single-page app, an SPA. It loads one page. Then it draws each tea's page with JavaScript, without asking the server for new HTML. The address still changes:
document.addEventListener("click", (event) => { const link = event.target.closest("a[data-tea]"); if (!link) return; event.preventDefault(); history.pushState({}, "", link.href); show(link.dataset.tea);});- Line 1 listens for clicks anywhere on the page.
- Lines 2 and 3 keep only clicks on a tea's link.
- Line 4 stops the browser from loading a new page.
- Line 5 changes the address with
history.pushState. Line 6 draws the tea's page.
Asha lands on /teas. She clicks Mint tea at 2,034 ms. Its photo has no size. The jump comes 805.3 ms after her click, and scores 0.0828. 206.5 ms later, she clicks Green tea. Its photo jumps the same way, 604.3 ms after the click. Both came more than 500 ms after a click, so both count.
Each page alone scored 0.0828: good. But what does Ravi's report say? That depends on how the page asks:
// The reports from Asha's visit to the tea appconst visit = { url: "/teas", cls: 0.1656 };const pages = [ { url: "/teas", cls: 0 }, { url: "/teas/mint", cls: 0.0828 }, { url: "/teas/green", cls: 0.0828 },];console.log(`One report for the visit: ${visit.url}, CLS ${visit.cls}`);for (const page of pages) console.log(`One report per page: ${page.url}, CLS ${page.cls}`);- Line 2 is web-vitals' usual report, sent when Asha left.
- Lines 3 to 7 are the reports with one per page.
- It prints
One report for the visit: /teas, CLS 0.1656. Then come three lines that startOne report per page:, for /teas, /teas/mint and /teas/green.
The usual report covers the whole visit. The two jumps came 810.8 ms apart, so they fell in one session window. CLS added them up: 0.1656, "needs improvement". And it filed all of it under /teas, the address Asha landed on. Its attribution even named a jump at 3,650.1 ms, on the green tea page.
web.dev's SPA guide says this is how the metrics first worked: "the URL associated with each metric measurement is the URL the user navigated to that initiated the page load."
Asha buys one train ticket at Hill Road and rides through two more stations. The rail company asks her to rate the bumpiest stretch. Her rating goes on Hill Road's record, even though the bumps came later. With a new ticket at each station, each stretch would get its own rating.
- In real life: The station where she bought her ticket
- In JavaScript: The address Asha landed on: /teas
- In real life: The stations she rode through
- In JavaScript: The app's pages: /teas/mint and /teas/green
- In real life: The bumpiest stretch
- In JavaScript: CLS: the worst session window
- In real life: A new ticket at every station
- In JavaScript: Soft navigations: one CLS per page
Chrome can now tell the pages apart. From Chrome 151, it spots a soft navigation: a move to a new page inside a single-page app. Three things must happen:
- The visitor clicks, taps or presses a key.
- The address changes.
- Something new is painted.
Each soft navigation gets a soft-navigation entry. It holds the new address and a navigationId: a number for that page. Chrome wrote two: /teas/mint at 2,034 ms and /teas/green at 3,045.8 ms, each at the moment of its click. Every layout-shift entry carries a navigationId too. So you can tell which page a jump happened on.
web-vitals uses them when you pass reportSoftNavs: true. Its README says CLS "is reset to measure again separate to the first page". To keep both views, ask for CLS twice:
// One report for the whole visit, the way CrUX's stable CLS counts itwebVitals.onCLS(sendVisit);// One report per page, soft navigations includedwebVitals.onCLS(sendPage, { reportSoftNavs: true });- Line 2 asks for the usual CLS: one per visit.
- Line 4 asks for one CLS per page. Each report's
navigationURLsays which page it's for. web-vitals sends each page's report as soon as the next page starts.
CrUX, Chrome's field data, still files the whole visit under the first address in its usual CLS. It also publishes an experimental CLS that splits it page by page. And DevTools ends a cluster at every navigation, soft ones included. Why it matters: in an SPA, check which page a jump really happened on before you fix the first one.
Here are the tea app's real reports, both ways:
/teas0.1656needs-improvementnavigate5,799.9 ms, page hidden#app>p.about3,650.1 ms0.0828completeweb-vitals' usual report: one CLS for the whole visit, sent when Asha left. Both tea pages' jumps are in it, under /teas.
Which clue do you need?
Each place you can look answers some questions and not others. Read each row across: where you look, what it tells you, and what it can't.
| Where you look | What it tells you | What it can't tell you |
|---|---|---|
| The field report, from web-vitals' attribution build | Which element moved in the biggest jump, when, and how far the page had loaded. It comes from real visits. | What pushed it. It can't see jumps inside an ad's iframe either. |
| The Layout shifts track, in a DevTools trace | Every jump you made happen, its score and cluster, and what ran just before it. | What real visitors did. It only shows this recording, on your computer. |
| A shift's sources | Up to five things that moved, each with its box before and after. | What made room. You find that by looking just above the first one. |
Now sort some questions by where you'd find the answer first:
- Which element moves most often for real visitors
- Whether real visitors' jumps come during the load or after it
- Which page of a single-page app jumps for real visitors
- What ran on the main thread just before the jump
- Which of your jumps fall in the same cluster
- How far each element moved, and which way
- Whether an element was pushed off the screen
Sort each question by where you'd look first.
Common mix-ups
- "If my test scores 0, real visitors get 0." No. Ravi's test scored 0. Asha scrolled, and her visit scored 0.1486.
- "largestShiftTarget is what caused the jump." No. It's the first element that moved. Asha's report named #review-15. Ben's photo, just above it, made the room.
- "The Layout shifts track shows every layout shift." No. Like CLS, it leaves out the shifts right after a click, tap or key press.
- "Scrolling excuses a jump." No. A scroll isn't input. Ben's photo jumped 303.7 ms after Asha stopped, and counted in full.
- "Scroll anchoring stops every jump while you scroll." No. It only hides changes above the anchor. Ben's photo grew below it, on the screen, and the reviews still jumped.
- "Each page of a single-page app gets its own CLS." No. The usual report gives the whole visit one CLS, under the first address. Per-page CLS needs soft navigations and reportSoftNavs.
- "A visit sends exactly one CLS report." No. Lesson 30.2's page sent two: one when Asha left, and one from 0 after she came back.
Practice exercises
Answer first, then use the hints.
Here are the sources of a smaller jump. What does the first line print?
const sources = [
{ node: "#review-9", previousRect: { y: 410, height: 104 }, currentRect: { y: 526, height: 104 } },
{ node: "#review-10", previousRect: { y: 760, height: 120 }, currentRect: { y: 0, height: 0 } },
];
for (const { node, previousRect, currentRect } of sources) {
if (currentRect.height === 0) console.log(`${node}: pushed off the screen`);
else console.log(`${node}: down ${(currentRect.y - previousRect.y).toFixed(1)} px`);
}#review-9: down 116.0 px. That's the height of one new review with its gap, as in the anchoring test. The second line prints #review-10: pushed off the screen, because its new box is all zeros.
Caveat arrived at 1,313.1 ms on Asha's page. If it had made a jump then, which load state would web-vitals report?
// web-vitals' rule, shortened, with the times of Asha's page load
const page = { domInteractive: 9.3, domContentLoadedEventStart: 9.3, domComplete: 2528.4 };
function loadState(time) {
if (time < page.domInteractive) return "loading";
if (time < page.domContentLoadedEventStart) return "dom-interactive";
if (time < page.domComplete) return "dom-content-loaded";
return "complete";
}
console.log(loadState(1313.1));dom-content-loaded. Caveat arrived while the page was still loading other files, like the ad's script. A jump then would show up on a reload in the lab.
In the Layout shifts track playground, pick lesson 30.2's page. At what time does its cluster end, in ms?
3,533.9 ms: exactly 1,000 ms after the last shift, inside the ad, at 2,533.9 ms. A cluster stays open for a second after its last shift, in case another one comes.
In the tea app's reports playground, pick One report per page. When was the report for /teas sent, in ms?
2,081.7 ms, with the page still visible. That's 47.7 ms after the soft navigation to /teas/mint at 2,034 ms. web-vitals closes the old page's CLS as soon as a new page starts.
Download the course's trace of Asha's visit to the tea app. Load it in DevTools' Performance panel. How many clusters does the Layout shifts track draw?
Two. web-vitals' usual CLS put both jumps in one window, 810.8 ms apart. DevTools ended the first cluster at the soft navigation to /teas/green, at 3,045.8 ms, so each page got its own cluster.
In the CSS Scroll Anchoring spec, which two values of the position property always put an element in an excluded subtree, so it's never picked as the anchor?
fixed and sticky. Such an element doesn't move with the page's content, so it would make a poor anchor. position: absolute is skipped too, but only when its containing block is outside the scrolling box.
Check your understanding
For each question, ask which clue it's about: the field report, the track, the sources, or a jump that came late.
Question 1 of 7What does the third line of the sources example print?
Read the code, then predict// The sources of Asha's jump: where each one was, and where it went const sources = [ { node: "#review-15", previousRect: { y: 323.59, height: 128 }, currentRect: { y: 558.33, height: 128 } }, { node: "#review-17", previousRect: { y: 555.59, height: 128 }, currentRect: { y: 790.33, height: 32.67 } }, { node: "#review-16", previousRect: { y: 463.59, height: 80 }, currentRect: { y: 698.33, height: 80 } }, { node: "#review-18", previousRect: { y: 695.59, height: 127.41 }, currentRect: { y: 0, height: 0 } }, ]; for (const { node, previousRect, currentRect } of sources) { if (currentRect.height === 0) console.log(`${node}: pushed off the screen`); else console.log(`${node}: down ${(currentRect.y - previousRect.y).toFixed(1)} px`); }Choose an answer to see the explanation.
Question 2 of 7What does largestShiftTarget name?
Choose an answer to see the explanation.
Question 3 of 7Ravi's test scored a CLS of 0. Asha's visit to the same page scored 0.1486. Why did the test miss the jump?
Choose an answer to see the explanation.
Question 4 of 7On DevTools' Layout shifts track, what does a bigger diamond mean?
Choose an answer to see the explanation.
Question 5 of 7One of a shift's sources has a currentRect of all zeros. What happened to that element?
Choose an answer to see the explanation.
Question 6 of 7A new review goes in at the top of the list, above the screen, while Asha reads further down. The page has the default CSS. What happens?
Choose an answer to see the explanation.
Question 7 of 7In the tea app, web-vitals' usual report gave /teas a CLS of 0.1656, though nothing on /teas itself moved. Why?
Choose an answer to see the explanation.
Key takeaways
- A CLS report from the field says what moved, when, and how far the page had loaded. It doesn't say what made room.
- Make the jump happen in the lab. Reload for jumps during the load. Use the page for jumps after it.
- On the Layout shifts track, each diamond is one shift, sized by its score. Clusters follow CLS's session windows.
- A shift's sources give each element's box before and after. Look just above the first one for the cause.
- Lazy content can jump while visitors scroll, and it counts in full. Scroll anchoring only hides changes above the screen.
- An SPA's usual CLS covers the whole visit, under the first address. Soft navigations give one CLS per page.
Remember the one-liner.
The browser tells you what moved; you find what made room, just above it.
Sources
The facts on this page come from these specs, docs and source files:
- Debug layout shifts, web.dev.
- attribution/onCLS.ts: the CLS attribution, web-vitals source, v6.2.3.
- getLoadState.ts: how far the page had loaded, web-vitals source, v6.2.3.
- onCLS.ts: when CLS is reported, web-vitals source, v6.2.3.
- Performance features reference: View layout shifts, Chrome DevTools.
- LayoutShiftsHandler.ts: the Layout shifts track's clusters, Chrome DevTools source.
- Layout shift culprits, Chrome for Developers.
- Layout Instability API, WICG.
- layout_shift_tracker.cc: sources sorted by the area they moved, Chromium source.
- Optimize Cumulative Layout Shift, web.dev.
- CSS Scroll Anchoring Module Level 1, W3C CSS Working Group.
- Measuring soft navigations, Chrome for Developers.
- Report metrics for soft navigations, web-vitals README, v6.2.3.
- How SPA architectures affect Core Web Vitals, web.dev.
- Experimental soft navigation metrics now available in CrUX, web.dev.
Coming next: Style recalculation. How the browser matches CSS selectors to elements, what makes that slow, and how to measure it.