Debugging Web Performance / Module 06

Module 6: Rendering Cost and Layout Shifts

Find what style, layout, paint and hit testing cost on a 60,000-element page, contain that cost to one row, and stop the Buy button from jumping.

Leo picked a seat on the stadium map, then put his finger down again to drag the map to the next block. For a moment, the map did not follow his finger. Then it jumped to catch up.

On the show page, he tapped Buy tickets as soon as it appeared. The page moved, and his tap landed on the show’s name.

“Two things moved, and neither was me,” Leo wrote.

Maya, Leo and TinyTickets are invented, and so are the numbers in their story.

This module is about the work the browser does after your JavaScript ends: style, layout, paint and the steps that put a frame on the screen. You’ll see why one changed seat costs a paint of 60,000 seats, why a drag can wait for it, and how containment keeps that work inside one row. Then you’ll stop the layout shifts that move the Buy button, and decide whether the seat map should stay in the DOM or move to a canvas.

After this module, you can:

  • name the rendering steps from style to the screen, and say which run on the main thread and which can run without it
  • recognize a forced synchronous layout in code and in a long animation frame, and remove it by reading before you write
  • cut the cost of a large DOM with CSS containment and content-visibility, and say when each one doesn’t help
  • choose between DOM elements and a canvas for a large interactive picture, and state what the canvas costs in accessibility
  • find the element and the cause behind a layout shift, and fix unsized images and late web fonts

What buyers saw when the map and the button moved

Neither symptom shows up well in Core Web Vitals. A drag isn’t an interaction, so INP doesn’t count it (Module 1). The Buy button’s jump does count in CLS, but it’s small.

Maya’s endpoint had both pages. In the last week, 1,240 CLS lines came from phones on show pages, with a 75th percentile of 0.098. That’s “good”, under the 0.1 line. Every one of them named html>body>main>p.when as largestShiftTarget, the date line under the show’s name.

On the seat map, the 75th percentile was 0.192, with #map as the target, and CrUX still said 0.25 (Module 1).

The INP lines from show pages told her more. Each one names the target of the page view’s slowest interaction (Module 1). Of 3,900 INP lines from phones on show pages, 310 named the h1, the show’s name, which has no handler. So those buyers were aiming at the button.

Pause and predict. Module 5 left a seat tap at about 390 ms on the phone profile, with almost no JavaScript in it. When a buyer drags the map right after a tap, how long can the map lag behind the finger, and what is the main thread doing meanwhile? Write a number down.

Reproduce the stutter and the jump in the lab

The lab app is Module 5’s, unchanged. Use the phone profile from Module 1: 412 × 823, device pixel ratio 1, touch, Slow 4G and 6x CPU, with Disable cache checked.

The runs behind this module used headless Chrome 157 on the 2019 laptop (Intel Core i7-9750H), driven through the DevTools Protocol, as in Modules 1 to 5. Each run loaded a page, waited for it to settle, and then tapped seats, dragged the map or recorded a trace. Each version of the code ran three times unless a line says otherwise. Your numbers will differ.

The seat map’s taps matched Module 5. Nine taps took 384–400 ms, with input delay 111–128 ms, processing 0–3 ms and presentation delay 267–278 ms.

The drag needed a setup of its own. A buyer’s finger usually lands on the map shortly after a tap. So each run picked a seat with a click() from the protocol, which runs the map’s own handler. At once, it started a touch drag of 600 px at 1,000 px per second.

A trace recorded both, and the script measured when the compositor first moved the map after the drag began. In three runs with the main thread idle, the map started to move 27–33 ms after the drag began. But in three runs right after a seat change, it started 218–232 ms after.

Figure 1 draws one of the runs right after a seat change on the main-thread timeline, at 20 ms per character as in Module 5.

time (ms)     0         200       400       600
              |         |         |         |
tap           v
main thread    [= paint=][l] [=paint=][h]
drag                        v
map moves                               >>>>>>>>

paint = Paint for the whole grid, about 175 ms each
l     = Layerize, 55 ms
h     = hit tests for the drag, 45 ms

Figure 1: the finger starts moving at 290 ms, and the map starts at 522 ms, after the second paint and the drag’s hit tests.

That’s the stutter Leo felt: the map waits, then jumps to where the finger already is. The second paint is the frame that Module 5’s yield added for the status line.

The show page doesn’t need a trick. In three loads, the first frame showed the text and the Buy button at y = 276 px. Then the browser learned the picture’s size, and everything below it moved down 213 px. The shift scored 0.098 each time.

But on the laptop, the picture usually arrives before the first paint, so the page never shows the button in its first place (Module 1).

What the browser does after your JavaScript

Module 2 named the rendering steps in a trace. This section explains what each one does, which thread runs it, and why its cost follows the number of elements.

The steps from a DOM change to the screen

Chrome’s rendering pipeline has more stages than DevTools shows, so the list below follows the trace names (RenderingNG architecture):

  1. Recalculate style (UpdateLayoutTree in the trace file) works out which CSS rules apply to each element that changed, and computes its styles.
  2. Layout computes the size and position of each box.
  3. Pre-paint updates the property trees: the transforms, clips, scroll offsets and effects that apply to each part of the page. It also marks what must be painted again.
  4. Paint records what to draw. Its output is a display list, a list of drawing commands such as “fill this rectangle with this color”, not pixels.
  5. Layerize splits the display list into layers that can move on their own, such as the contents of a scrolling box.
  6. Commit copies the display list and the property trees to the compositor.

These six run on the main thread. After the commit, raster turns the display list into pixels, tile by tile, on other threads. The GPU process then draws the tiles into a frame.

The compositor thread is the thread in the page’s renderer process that turns committed layers into frames. It can produce a new frame without the main thread when only a scroll offset, a transform or an opacity changed. Those change how the layers are placed, not what’s in them (Inside look at modern web browser, part 3).

Since 2011, Chrome has scrolled on that thread (RenderingNG). Figure 2 shows which thread does what.

main thread                              compositor thread       GPU process
[JS] -> [style] -> [layout] -> [pre-paint]
     -> [paint] -> [layerize] -> [commit] --> [raster tiles] --> [draw frame]
                                              [scroll, transform,
                                               opacity: new frame
                                               without the main thread]
[hit test: which element is under the finger]

Figure 2: the main thread records what to draw; the compositor can move it and draw it again on its own.

Not every change runs every step. web.dev’s simplified model lists three paths (rendering performance). Figure 3 lists them.

What the change touches Example properties Steps it runs
Geometry width, height, top, left, adding an element style, layout, paint, composite
Paint only color, background-color, box-shadow style, paint, composite
Neither transform, opacity, on their own layer style, composite

Figure 3: a seat’s color change skips layout, but not paint. No current official table lists every property; record a trace to check one.

The seat map’s tap is in the second row: one class changes a background color. So the tap had no layout of note, and Module 5’s traces showed 36 ms or less of style, layout and pre-paint. The cost was in paint.

Why one seat paints 60,000

Paint walks the boxes in paint order and appends drawing commands. Chrome keeps the previous display list as a cache. A box that didn’t change gives back its cached commands instead of being painted again (Blink paint README).

That cache saves the drawing, but not the walk. Each of the 60,000 seats is still visited, and its cached commands are copied into the new list. In Module 5’s code, every seat is a direct child of one grid, so one changed seat means a walk over 60,000 boxes. That walk was 203 ms of Paint at 6x CPU, then 56 ms of Layerize over the new list.

Chrome can skip a whole group of boxes at once. The same README describes subsequence caching: when a paint layer hasn’t changed, Chrome copies its whole stretch of the display list in one step, without visiting the boxes inside. A box needs a paint layer of its own for that. But the seat map’s single grid has none.

Why the finger waits: hit testing

Hit testing is the browser’s search for the element under a point, such as the place a finger touched. It runs on the main thread and walks the boxes from the top of the paint order. Before Chrome looks inside a box, it runs a fast check, MayIntersect, and skips the box with everything in it when the point can’t be there (Chromium source, layout_box.h).

In the seat map, the 60,000 seats are siblings in one grid, so no seat can be ruled out by its parent. That’s why each tap in Module 5 started with 10 hit tests of 89 ms in all, most of the input delay.

A drag needs hit testing too. In every drag trace here, the compositor moved the map only after four or five hit tests on the main thread, about 45 ms in all. When the main thread was busy painting, those hit tests waited for the paint to end, and so did the map. But once the drag had started, the compositor kept moving the map every 16–19 ms, also during main-thread paints.

Rule: The main thread paints and hit tests; the compositor scrolls. A scroll that must start on a busy main thread starts late.

Forced synchronous layout

The browser usually runs style and layout once per frame, after your code. But your code can make it run them earlier. Forced synchronous layout is the browser running style and layout in the middle of your JavaScript. It happens when the code reads a geometry value, such as offsetTop, after a change made the layout stale (web.dev).

The read itself is cheap when nothing is stale. But it costs a full style and layout when something is. Layout thrashing is doing this in a loop: change, read, change, read, so each read forces another layout.

Reads that force layout include offsetTop, offsetWidth and the other offset* and client* properties, getBoundingClientRect(), scrollTop and scrollIntoView(), focus(), innerText and getComputedStyle(). Chrome doesn’t publish an official list. The most complete one is a list kept by a Chrome DevTools engineer (Paul Irish, “What forces layout / reflow”).

Pause and predict. Paste this into the Console on the seat map. It shrinks 20 seats, one per 15 rows, and reads each one’s offsetTop right after the change. Then it shrinks 20 other seats and reads them all at the end. How long does each half take on the phone profile?

const seats = document.querySelectorAll('#map .seat');
const shrink = (seat) => { seat.style.width = '5px'; };
let start = performance.now();
for (let i = 0; i < 20; i++) { shrink(seats[i * 3000]); seats[i * 3000].offsetTop; }
const interleaved = performance.now() - start;
await new Promise((r) => setTimeout(r, 1000));
start = performance.now();
for (let i = 0; i < 20; i++) shrink(seats[i * 3000 + 1]);
for (let i = 0; i < 20; i++) seats[i * 3000 + 1].offsetTop;
const batched = performance.now() - start;
console.log(`interleaved: ${interleaved.toFixed(0)} ms, batched: ${batched.toFixed(0)} ms`);
Answer

Three runs on Module 5’s seat map printed:

interleaved: 7124 ms, batched: 339 ms
interleaved: 7394 ms, batched: 337 ms
interleaved: 7223 ms, batched: 336 ms

Each read after a change forced a layout of the whole 60,000-item grid, about 360 ms at 6x CPU, 20 times. The batched half changed all 20 seats first, so the first read forced one layout and the other 19 found it fresh.

So the fix is the order: do all the reads first, then all the writes, or read once before the loop. web.dev’s other way out is to compute the value without asking the layout at all. On the seat map, a seat’s position is (number - 1) * 7 px across and (row - 1) * 7 px down, so no code needs to read it.

Rule: Read layout before you change anything in the same task. A read after a change costs a full layout.

Containment: telling the browser what a change cannot reach

Even with rows, paint has to visit every seat, because the browser can’t know what one seat’s change might affect. But CSS lets you promise it.

CSS containment is a promise, set with the contain property, that a box’s contents don’t affect anything outside it. The browser can then handle that box on its own (CSS Containment Level 2, W3C Working Draft, 2022). Its main types:

  • layout: the box’s inside doesn’t change the layout outside it.
  • paint: nothing inside is drawn outside the box, so its contents are clipped to it.
  • style: counters and quotes inside don’t reach outside.
  • size: the box is sized as if it were empty, so its size doesn’t depend on its contents.

contain: content is layout, paint and style together. contain: strict adds size.

The spec gives paint and layout containment one more effect: each creates a stacking context. In Chrome, a box that is stacked, or that clips its contents, gets a paint layer of its own (Chromium source, LayoutBox::LayerTypeRequired()). A paint layer is what the paint cache needs to copy a row in one step.

Containment helps only where there are boxes to contain. Module 5’s seats are 60,000 siblings in one grid, so a promise about the grid would cover all of them at once. That’s why they need a level between the map and the seats: rows, which also help hit testing.

content-visibility: skipping what is far from the screen

content-visibility is a CSS property that lets the browser skip the rendering of an element’s contents. With content-visibility: auto, the element always gets layout, style and paint containment. While it isn’t “relevant to the user”, the browser also skips its contents: no style, no layout, no paint, no hit testing (CSS Containment Level 2).

An element is relevant when it’s on screen or near it, focused, selected or in the top layer. The spec suggests a margin of 50% of the viewport around the screen. But Chromium uses 150%: its source creates the observer for these elements with a margin of kViewportMarginPercentage, commented as “150% margin (on the viewport)” (Chromium source, display_lock_document_state.cc, read 2026-11-18).

A skipped element has size containment, so it would collapse to 0 px. contain-intrinsic-size gives it a size to use while its contents are skipped, such as contain-intrinsic-size: 1399px 6px. With auto in front of the length, the browser remembers the last size it rendered and uses that instead (MDN).

Skipped content stays in the DOM and in the accessibility tree, and find in page still finds it. But with content-visibility: hidden, the contents stay skipped even on screen, and they aren’t findable. On web.dev’s travel blog example, auto cut the first rendering from 232 ms to 30 ms (web.dev).

Find the cause in the trace

Module 2 read a tap’s trace. Here you’ll read the same tasks for what they visit, then check two causes that aren’t there.

  1. Turn on Paint flashing. In DevTools, open the Rendering tab (More tools, then Rendering) and check Paint flashing. Tap one seat. The areas Chrome repaints flash green (Chrome for Developers).

  2. Record a tap and a drag. In the Performance panel, record while you tap a seat and start dragging the map at once. The first task after the tap is the tap’s own task: hit tests and the handler. Two Paint tasks follow, one for the seat’s frame and one for the status line’s frame.

  3. Read the Paint task. In one trace, the first paint after the tap took 203 ms, then Layerize 56 ms. But only one seat changed color. Open the Summary of the Paint event; it covers the map’s whole area, because the map is one grid.

Pause and predict. Suppose you split the 60,000 seats into 300 row elements of 200, and change nothing else. Which of the tap’s three parts gets shorter: the input delay, the processing, or the presentation delay?

Answer

The input delay. With rows, the hit tests fell from 89 ms to 1 ms in one trace, because a whole row can be ruled out when the point isn’t inside it. But the paint didn’t change: 196 ms and 195 ms for the two frames, because the rows have no paint layers of their own and every seat is still visited.

Six taps took 264–288 ms, with input delay 18–26 ms and presentation delay 246–264 ms. Fix 1 below is that change.

  1. Read the drag. On the Main track, look between the tap’s second Paint and the first frame in which the map has moved. In the run of Figure 1, the map started moving 232 ms after the drag began. In between, the second Paint ran 173 ms, then four Hit test events ran 45 ms.

  2. Rule out forced layout. The Forced reflow insight lists any JavaScript that read geometry after a change, with its function and total time. It fails when it finds one (Chrome for Developers, 2025). Long animation frames carry the same number per script in forcedStyleAndLayoutDuration (Module 5).

In the tap and drag runs here, no frame listed a script over 5 ms, except Scheduler.yield.then for 9 ms with forcedStyleAndLayoutDuration 0. So forced layout isn’t the cause here.

  1. Rule out the element count as a rule. The Optimize DOM size insight in DevTools and Lighthouse 13 flags a large DOM only when one style or layout event passes 40 ms (Chrome for Developers, 2025).

Older Lighthouse versions warned at about 800 elements and failed at about 1,400; many articles still quote those numbers. Module 2 saw this insight list a layout of 60,008 objects on the first load. But it says how big, not what to change.

  1. Find the jump. Reload the show page with the Performance panel recording. On the Layout shifts track, a purple diamond marks the shift at about 1.31 s. Hover over it to highlight what moved; click it for its score and elements. The Layout shift culprits insight names the likely cause: an image without dimensions, stadium.jpg, as Module 2 saw on the seat map (Chrome for Developers).

Figure 4 is the show page’s load, from one run, on the page-load timeline.

time (s)     0         1         2
             |         |         |
show.html    ======
styles.css         ======
show.css           ======
analytics.js       ======
show.js            ============  (defer)
stadium-400        =======  (no width or height)
                   ^ TTFB 0.57 s
                          ^ shift 0.098 at 1.32 s, Buy 276 -> 489 px
                          ^ FCP 1.33 s, LCP 1.34 s

Figure 4: the picture arrives about 100 ms after the stylesheets, and the first frames show the button 213 px above where it ends.

The shift’s entry listed five elements that moved, all below the picture: the h1, p.when, the description, p.price and a.buy. The picture itself isn’t in the list. That’s because it didn’t exist in the previous frame, and an element that appears doesn’t count as shifted.

Rule: Look at what was painted before the shift. An element moved because something above it changed size.

The fixes, one change at a time

Every number below comes from the phone profile in headless Chrome 157, page loads in threes, unless a line says otherwise.

Fix 1: put the seats in rows

The map needs a level between the map and the seats. In public/seats.js, replace the two lines that build the map:

// One element per stadium row: hit testing and painting can then deal with one row at a time.
const row = `<div class="row">${'<span class="seat"></span>'.repeat(200)}</div>`;
map.innerHTML = row.repeat(SEAT_COUNT / 200);
const elements = [...map.querySelectorAll('.seat')];

In public/styles.css, replace the #map and .seat rules. The map becomes a grid of 300 rows, and each row a flex line of 200 seats:

#map {
  display: grid;
  gap: 1px;
  height: 60vh;
  overflow: auto;
}
.row {
  display: flex;
  gap: 1px;
}
.seat { flex: none; width: 6px; height: 6px; background: #3a7bd5; }

Seat id still indexes elements, so pickSeat and renderSeat() work unchanged. The map looks the same, with 300 more elements.

This is the change from the prediction above. In two loads of three taps, taps took 264–288 ms, with input delay 18–26 ms, processing 0–3 ms and presentation delay 246–264 ms. Hit testing fell from 89 ms to 1 ms; the two paints stayed at about 195 ms each.

The first load got cheaper too. Style and layout in the load’s long frame took 1,101–1,105 ms instead of 1,223–1,265 ms, and LCP was 3,640–3,688 ms instead of 3,836–3,908 ms. But the layout mode matters here. A version with each row as a 200-column grid was slower than the single grid, with 1,603–1,696 ms of style and layout and an LCP of 4,168–4,216 ms.

The forced-layout snippet changed most. In two runs it printed:

interleaved: 99 ms, batched: 35 ms
interleaved: 91 ms, batched: 37 ms

Each forced layout now cost about 5 ms instead of 360 ms.

The runs fit one explanation: Chrome keeps the layout result of a box whose inputs didn’t change. A seat’s new width is an input to its row, not to the 299 other rows. But with one grid, it was an input to the grid and all 60,000 items in it.

But the rule to read before you write still stands: 20 forced layouts still cost more than twice the batched version.

Fix 2: contain each row’s paint

Add one line to .row:

.row {
  display: flex;
  gap: 1px;
  /* Nothing in a row is drawn outside it, so Chrome can keep each row's paint apart. */
  contain: paint;
}

Taps now took 88–144 ms in nine taps, with input delay 21–44 ms, processing 0–3 ms and presentation delay 67–101 ms. In one trace, the paint after the tap took 10 ms instead of 196 ms, and the status line’s frame 12 ms. Layerize stayed at 55 ms, because it still goes over the display list of the whole map.

Figure 5 is the same tap and drag as Figure 1, from one run.

time (ms)     0         200       400       600
              |         |         |         |
tap           v
main thread   [pl] p                    NEW
drag                 v
map moves            >>>>>>>>>>>>>>>>>>>>>>>>>>

p = Paint, about 10 ms each
l = Layerize, 55 ms

Figure 5: the seat change costs two short paints, and the drag finds the main thread free.

Before Fix 2, a drag that began in the half second after a tap had to wait for two full paints. Now the main thread is busy for about 80 ms after a tap. So in three runs that began the drag right after a seat change, the compositor moved the map 3–4 ms after the finger.

Three ways to contain the rows

contain: paint is the smallest promise that gives the paint a layer per row. contain: content and content-visibility: auto promise more. Figure 6 compares them on the same flex rows, two loads of three taps each, and two drags.

Rows with Tap First load: the long frame LCP Main-thread tasks over 30 ms during a 600 px drag
nothing (Fix 1) 264–288 ms 1,924–1,952 ms 3,640–3,688 ms none
contain: paint 96–104 ms 1,918–1,944 ms 3,640–3,680 ms none
contain: content 96–104 ms 1,952–1,974 ms 3,672–3,700 ms none
content-visibility: auto 96–104 ms 1,777–2,154 ms 3,440–3,920 ms three or four, 191–456 ms each

Figure 6: on this map, skipping rows saves little at load and adds main-thread work to every drag. These are separate runs from Fix 2’s nine taps.

contain: content measured the same as contain: paint, and promises more, so TinyTickets uses the smaller one. But content-visibility: auto needs a closer look.

Two facts explain its row. The map is 2,100 px tall, and Chromium keeps elements within 150% of the viewport rendered, 1,234 px above and below an 823 px screen. A Console check after the load found 237 of 300 rows rendered, and all 300 once the map was scrolled 1,000 px. So almost nothing was skipped, and the load varied more between runs than it changed.

And when a skipped row comes into range during a drag, Chrome renders it then, on the main thread. The compositor kept the drag smooth, with frames 18–19 ms apart. But a tap during those tasks would wait up to 456 ms.

The choice flips when the content is many screens long: a long list of shows, the text of a long page, a venue map drawn large enough for fingers. Then most of it is skipped, and the work during scrolling is small next to the work saved at load.

The count of rendered rows came from this check, which works on any page that uses content-visibility:

const rows = [...document.querySelectorAll('#map .row')];
const rendered = rows.filter((row) => row.firstElementChild.checkVisibility({ contentVisibilityAuto: true }));
console.log(`${rendered.length} of ${rows.length} rows rendered`);

checkVisibility({ contentVisibilityAuto: true }) returns false for an element inside a skipped subtree. Ask it about a child of the row, not the row, because the row’s own box is always rendered.

The costs of Fixes 1 and 2

  • The promise must be true. With contain: paint, anything a seat draws outside its row is cut off: a focus ring, a tooltip, a badge on the seat. Wrong containment hides content; it doesn’t slow the page.
  • More elements and a fixed structure. The rows add 300 elements, and the code now assumes 200 seats per row. A venue with rows of different lengths needs the row lengths in the data.
  • The first load is still long. The load’s long frame is about 1.9 s: 0.8 s of script and 1.1 s of style and layout for 60,000 seats. Containment keeps later changes small; it doesn’t make the first layout of every seat cheaper.
  • Layerize is left. About 55 ms of each tap’s frame is still Layerize over the whole map.

Does the yield still earn its place?

Module 5 kept await yieldToMain() before renderSummary(), and asked this module to check again. The yield adds a frame, and before Fix 2 every frame cost a full paint of the grid: 169–183 ms in the drag runs and 203 ms in the tap trace. But now a frame’s Paint is about 10 ms. A variant without the yield measured the trade:

Rows with contain: paint Tap, nine taps Processing Paint tasks after one tap, one trace
With the yield 88–144 ms 0–3 ms two: 10 ms and 12 ms
Without the yield 104–120 ms 6–9 ms one: 14 ms

Figure 7: once a frame is cheap, the yield no longer makes the tap measurably faster.

Without the yield, nine taps took 104–120 ms, against 88–144 ms with it. Processing grew from 0–3 ms to 6–9 ms, because the count of free seats now runs inside the tap. One frame replaced two: 14 ms of Paint and 64 ms of Layerize in that trace. The ranges overlap, so in these runs the yield no longer makes the tap faster.

Without the yield, the seat, its label and the status line change in the same frame. That removes a cost Module 5 named: for one frame, the screen and the screen reader no longer disagree about the seat. So TinyTickets removes the yield. Replace the click listener, and delete yieldToMain(), which nothing calls any more:

map.addEventListener('click', function pickSeat(event) {
  const id = elements.indexOf(event.target);
  if (id === -1 || seats[id].sold) return;
  picked.has(id) ? picked.delete(id) : picked.add(id);
  renderSeat(seats[id]);
  renderSummary();
});

The choice flips back when the work after the seat grows, such as a price total that calls the server, or when a frame becomes expensive again. Then Module 5’s pattern applies: change what the buyer waits for, yield, and do the rest.

DOM or canvas for the seat map

The first load is still a frame of about 1.9 s, and 60,320 elements are the reason. A canvas would draw the same map as one element. But before you decide, measure what it buys.

A variant drew the seats with fillRect() on one <canvas> of 1,399 × 2,099 px, and found the tapped seat from the tap’s position. This is the core of it:

// Excerpt from the canvas variant, not part of the lab.
const COLORS = { free: '#3a7bd5', sold: '#c7c7cc', picked: '#e8590c' };
function renderSeat(seat) {
  const state = seat.sold ? 'sold' : picked.has(seat.id) ? 'picked' : 'free';
  ctx.fillStyle = COLORS[state];
  ctx.fillRect((seat.number - 1) * 7, (seat.row - 1) * 7, 6, 6);
}
map.addEventListener('click', function pickSeat(event) {
  const x = event.offsetX, y = event.offsetY;
  if (x % 7 >= 6 || y % 7 >= 6) return; // the gap between seats
  const id = Math.floor(y / 7) * 200 + Math.floor(x / 7);
  // ... the rest as in the DOM version
});

Figure 8 compares it with the DOM map after Fixes 1 and 2.

Seat map Elements Tap First load: the long frame LCP
DOM, one grid (Module 5) 60,020 384–400 ms 2,109–2,181 ms 3,836–3,908 ms
DOM, rows with contain: paint, no yield 60,320 104–120 ms 1,915–1,932 ms 3,656–3,688 ms
One <canvas> 21 16–24 ms 236–249 ms 1,552–1,580 ms

Figure 8: the canvas is faster on every line. The canvas taps are from two loads; taps under 16 ms aren’t reported by Event Timing, so only three appear.

But the cost is everything the browser knew about the seats. A canvas is one image to the accessibility tree, to the keyboard and to find in page. The HTML Standard says authors “should not use the canvas element in a document when a more suitable element is available”.

When they do, they must provide fallback content: elements inside the <canvas> that aren’t drawn but give assistive technology the same function as the picture. That includes a focusable element for each focusable part (HTML Standard, canvas). For this map, that’s 60,000 focusable seats again, or another way to pick a seat, such as a list of free seats by section.

The DOM map isn’t accessible today either. Each seat is a <span> with an aria-label. WAI-ARIA 1.2 lists the generic role of a <span> under roles that can’t be named, so screen readers may ignore those labels (WAI-ARIA 1.2). No seat can take keyboard focus.

The difference is the starting point. In the DOM, the seats exist and can be given a role and focus. But in a canvas, everything must be built a second time, and kept in sync with the picture.

So TinyTickets keeps the DOM for now, and gives the seats real roles in a later change. The choice flips when the first load matters more than the seat-by-seat tree, and the team builds the accessible way to pick a seat first. A venue several times larger, or a map that must zoom and pan smoothly, would push the same way.

SVG sits between them: each seat is an element in the DOM and can carry a role and a name, so it shares the DOM’s costs. A research run on an unthrottled laptop built 60,000 SVG <rect> elements in about 400 ms, against about 350 ms for <div>s.

Fix 3: give the pictures their size

The jump on the show page, and the 0.192 shift on the seat map, have one cause. The <img> has no width or height, so until the picture’s first bytes arrive, the browser lays it out at 0 px tall. When the size arrives, everything under it moves.

When an <img> has width and height attributes, all browsers give it a default aspect-ratio from them, before any byte of the image arrives (web.dev, optimize CLS, updated 2025-02-07). The CSS sets the width, and the height follows from the ratio. Every file in the srcset is 16:9, so one pair of numbers fits them all.

In public/show.html and public/seats.html, add the attributes to the <img>:

<img src="/stadium.jpg" width="1600" height="900"

In public/styles.css, add height: auto, so the CSS width wins and the height comes from the ratio instead of the attribute’s 900 px:

img { display: block; width: 100%; height: auto; }

In three loads each, the show page’s shifts summed to 0.000, and so did the seat map’s, from 0.098 and 0.192. The Buy button sat at y = 491 px from the first frame. LCP didn’t change: 1,324–1,332 ms on the show page, 3,656–3,688 ms on the seat map.

The costs of Fix 3:

  • One ratio for every file. If an art-directed <source> uses a different ratio, it needs its own width and height on that <source>, or the space reserved is wrong and the page shifts by the difference.
  • The numbers must be kept true. A template that changes the picture’s ratio without changing the attributes reserves the wrong space.
  • Space for content that may not come. The same idea for a late banner or an embed is a min-height. If the content never arrives, the reserved gap stays empty.

When the cause is a web font

TinyTickets uses the system font, so this lab has no font shift. But if a show page loads the organizer’s display font, it can have one.

While the font downloads, the browser shows the text in a fallback font, or no text. When the font arrives, the text is laid out again. If its lines wrap differently, everything below moves, and that shift counts in CLS (web.dev, optimize CLS).

font-display is the @font-face descriptor that decides what the browser shows while a font loads, and whether it swaps the font in when it arrives.

CSS Fonts 4 defines three periods (CSS Fonts Level 4, Editor’s Draft, November 2026). In the block period, the text is invisible. In the swap period, the fallback shows and is replaced when the font arrives. In the failure period, the fallback stays.

Figure 9 lists the values with web.dev’s numbers.

font-display Block period Swap period Can shift the page late
block 2–3 s (the spec recommends 3 s) infinite yes
swap 0 ms (the spec: 100 ms or less) infinite yes
fallback 100 ms 3 s yes, in the first 3 s
optional 100 ms none no

Figure 9: only optional promises never to move the page. Sources: web.dev, font best practices, CSS Fonts 4. Browsers may use other durations.

Three fixes work together:

  • Preload the one font that matters, with crossorigin, even for a font on your own origin, because fonts are fetched in CORS mode: <link rel="preload" href="/fonts/display.woff2" as="font" type="font/woff2" crossorigin> (MDN). Since Chrome 83 (2020), a preloaded font with font-display: optional may hold the first render for up to 100 ms. It’s then used on the first frame or not at all (web.dev).
  • Use optional for text where the font is a nice-to-have. The cost is that a slow first visit shows the fallback for the whole page view.
  • Match the fallback to the font. Font metric overrides are @font-face descriptors that change the metrics of a local fallback font: size-adjust scales its glyphs, and ascent-override, descent-override and line-gap-override set its line metrics (Chrome for Developers). When the fallback takes the same space as the web font, the swap moves nothing.

The Capsize library computes the overrides from both fonts’ metrics. For Inter over Arial, createFontStack from @capsizecss/core 4.1.3 printed this in a research run on 2026-11-18:

font-family: Inter, "Inter Fallback", Arial
@font-face {
  font-family: "Inter Fallback";
  src: local('Arial'), local('ArialMT');
  ascent-override: 90.4365%;
  descent-override: 22.518%;
  line-gap-override: 0%;
  size-adjust: 107.1194%;
}

Its cost is that it depends on the fallback being installed. If a device doesn’t have Arial, it uses another font, and the match is gone. DevTools’ Rendering tab has Disable local fonts to test that case. Safari 17 supports size-adjust but, as of Safari 27.1, not the three other overrides, so the match there is partial.

Confirming it in the field

Maya shipped the three fixes together. A week later, her endpoint had 2,150 INP lines from phones on the seat map, with a 75th percentile of 150 ms, “good” for the first time. Presentation delay was still the largest part in most of them, now about 70 ms of Layerize and paint.

On show pages, the 75th percentile of CLS from phones was 0.000, and 6 of 4,020 INP lines named the h1, against 310 the week before. The seat map’s CLS lines said 0.000 too. But CrUX still showed the old numbers, because its 28-day window held three weeks from before the release.

No metric covered the drag. Leo did: “The map follows my finger now,” he wrote.

In Firefox and Safari

  • CLS and layout shift entries are Chromium-only. Firefox and Safari report no CLS at all, so field CLS covers only Chromium users (Module 1).
  • contain works in Chrome 52, Firefox 69 and Safari 15.4. Safari scopes contain: style for quotes only from Safari 27.
  • content-visibility works in Chrome 85, Firefox 125 and Safari 18. In Safari 18, text skipped by auto wasn’t found by find in page; Safari 26.0 fixed it. With that fix, the feature became Baseline newly available on 2025-09-15 (web.dev, Safari 26.0 release notes). contain-intrinsic-size with auto works in Chrome 117, Firefox 117 and Safari 17.
  • width and height to aspect ratio work in all three.
  • Font metric overrides: Chrome 87 and Firefox 89; Safari hasn’t shipped them. size-adjust: Chrome 92, Firefox 92, Safari 17.
  • The 150% margin is Chromium’s. Other engines choose their own margin, so the number of rows they render near the screen can differ.

The support versions come from MDN’s browser compatibility data, version 8.1.9.

What changed recently

  • 2020, Chrome 85: content-visibility and contain-intrinsic-size shipped in Chrome. Chrome 88 (2021) stopped counting content-visibility: auto content as layout shifts when it’s rendered (CLS changelog).
  • 2021: Chrome finished CompositeAfterPaint, which moved the choice of layers to after paint: the Layerize step in today’s traces (BlinkNG).
  • 2023, Chrome 117: the auto keyword of contain-intrinsic-size.
  • 2025-09-15: content-visibility became Baseline newly available, with Safari 26.
  • 2025-10-10, Lighthouse 13: the DOM size audit moved into the Optimize DOM size insight, which looks at the time of style and layout events instead of an element count (Lighthouse docs). The Forced reflow and Layout shift culprits insights have pages of their own from the same month.
  • 2026-02, Chrome 145: layout shift sources are sorted by the area they moved, largest first, and their rectangles are in CSS pixels instead of device pixels (changelog).

Online tools for this step

The Layout shifts track and the Rendering tab in DevTools. The Performance panel’s Layout shifts track draws each shift as a purple diamond, groups shifts into clusters, and highlights the moved elements on hover. The Layout shift culprits insight names likely causes. The Rendering tab shows the same work live: Paint flashing in green, Layout shift regions in purple, Layer borders, Frame rendering stats and Scrolling performance issues (Performance panel reference).

  • Data: lab, on your machine.
  • Limit: one page load or one session at a time. Paint flashing shows where Chrome painted, not how long it took; for that, record a trace.
  • When something else is better: it’s the first stop for any page you can open. Use the next two tools for a URL you want to test from outside, without your machine’s fonts, cache and speed.

CLS Debugger on webvitals.dev. You enter a URL. It loads the page in Chromium on an emulated phone (Moto G Power, 6x CPU, slow 3G) and on a desktop. It marks the shifted regions and lists the elements by their share of the score. It also shows CrUX field data for the URL and the origin.

  • Data: lab for the load, plus CrUX field data.
  • Limit: the page load only, so no shifts after a tap or a scroll; shifts inside iframes aren’t counted. Pages over 30 s fail, and bot protection can block it. Reports are public to anyone with the link for 14 days.
  • When DevTools is better: for any page that isn’t public, and for shifts after the load. Never paste a private URL into it.

Layout Shift GIF Generator. You enter a URL and choose phone or desktop. It loads the page with simulated 3G and CPU throttling and returns an animated GIF with the shifting elements marked, and the CLS score. The same tool is on npm as layout-shift-gif.

  • Data: lab, the load only.
  • Limit: a GIF can take minutes, and it’s hard to read on a page where much moves. It shows what moved, not why.
  • When DevTools is better: to find the cause. The GIF is useful to show the problem to someone like Leo, who will never open DevTools.

Check yourself

Debugging scenario

Omar adds a row label to the seat map. While the buyer drags, the row nearest the middle of the map gets the class near, which makes its seats 8 px tall. His scroll listener does this, for the 70 rows in view:

// Excerpt: Omar's scroll listener.
for (const row of visibleRows) {
  const middle = row.offsetTop + row.offsetHeight / 2 - map.scrollTop;
  row.classList.toggle('near', Math.abs(middle - map.clientHeight / 2) < 4);
}

On the phone profile, with Fixes 1 and 2 in place, the drag itself is smooth. But the label lags behind, and a tap during a drag takes about 500 ms. Long animation frames during the drag show one script per frame:

DIV#map.onscroll (event-listener) 410 ms, forcedStyleAndLayoutDuration 395 ms

What makes the listener slow, why is the drag still smooth, and what would you change?

Hint 1

Look at the order of reads and writes inside one turn of the loop, and then across two turns.

Hint 2

With rows, one forced layout cost about 5 ms in this module’s runs. How many does the loop force?

Answer

Layout thrashing. Each turn reads offsetTop and offsetHeight, then toggles a class that can change a row’s height. So the next turn’s read finds the layout stale and forces another one. Seventy rows give about 70 forced layouts, and at about 5.6 ms each that’s the 395 ms of forcedStyleAndLayoutDuration.

The drag stays smooth because the compositor scrolls the map without the main thread, once the drag has started. But the label is drawn by the main thread, so it lags, and a tap waits behind the 410 ms listener.

Read first, then write: compute every row’s middle in one loop, then toggle the classes in a second loop. Better, read nothing: rows are 7 px apart, so the middle row is Math.floor((map.scrollTop + map.clientHeight / 2) / 7), and only two rows change class per frame, the old one and the new one.

Review questions

  1. Which of these run on the main thread: style, layout, paint, hit testing, raster, a scroll that has already started? What can the compositor do while the main thread paints?
  2. In Module 5’s seat map, one seat changed color and Paint took 203 ms. Why didn’t the rows alone shorten it, while contain: paint on the rows did?
  3. A loop sets element.style.height and then reads element.offsetHeight for 100 elements. Why is it slow, and what are two ways to fix it?
  4. content-visibility: auto on 300 rows of a 2,100 px map barely changed the first load in Chrome. Why, and when would it help?
  5. What does a canvas seat map need so that a buyer with a screen reader can still pick a seat? And why do width, height and height: auto stop the shift of an <img> whose srcset files share one ratio?
Answers
  1. Style, layout, paint and hit testing run on the main thread; raster runs on other threads, and a started scroll runs on the compositor thread. While the main thread paints, the compositor can keep scrolling and draw frames from the layers it already has, but it can’t show anything new.
  2. Rows gave the hit test a level to rule out, but paint still visited every seat to copy its cached commands. Paint containment gives each row a paint layer, so Chrome copies an unchanged row’s commands in one step and repaints only the changed row.
  3. Each read after a write forces a full style and layout, 100 times. Do all the reads first and all the writes after, or compute the values without reading layout.
  4. Chromium keeps elements within 150% of the viewport rendered, and most of the 2,100 px map is within that range, so almost nothing was skipped. It helps when the content is many screens long, so most of it is far from the viewport.
  5. Fallback content inside the <canvas>: focusable elements that give the same function, or another accessible way to pick a seat. For the image, the attributes give the box an aspect ratio before the image arrives, and height: auto lets the CSS width decide the height. One ratio for all files means one pair of numbers is right for each.

Lab: contain the map and stop the jump

Time: about 15 minutes. You’ll need the lab app from Module 5, Chrome and Node.js. The finished code for this module is in the course repository, folder module-06/.

  1. Start the server with node server.js. Open http://localhost:8080/seats.html in Chrome, open DevTools, and set the phone profile: 412 × 823 with touch, CPU “6x slowdown”, Network “Slow 4G”, Disable cache checked.
  2. In the Rendering tab, check Paint flashing and Layout shift regions. Reload, then tap one seat. Predict before you tap: how much of the map will flash green?
  3. Record a trace while you tap a seat and start dragging the map right after. Find the two Paint tasks and the Hit test events before the map starts moving. Write down the Paint durations.
  4. Paste the forced-layout snippet from “Forced synchronous layout” into the Console. Write down both numbers.
  5. Apply Fix 1. Reload and record a tap again. Which part of the tap changed, and which didn’t?
  6. Apply Fix 2. Repeat steps 3 and 4. Then replace contain: paint with content-visibility: auto; contain-intrinsic-size: 1399px 6px;, reload, and run the rendered-rows check. Put contain: paint back, and remove the yield.
  7. Apply Fix 3. Open show.html, reload with the Performance panel recording, and check the Layout shifts track. Then switch to another tab and back, and find the last CLS lines in vitals.ndjson.
Results from one run

These come from headless Chrome 157 on a 2019 laptop (Intel Core i7-9750H), through the DevTools Protocol, not the DevTools UI. Paint flashing and the Layout shift regions weren’t checked. Your numbers will differ.

  • Step 3: Paint 203 ms for the seat’s frame and 203 ms for the status line’s frame; four or five hit tests, about 45 ms, before the map moved.
  • Step 4: interleaved: 7124 ms, batched: 339 ms.
  • Step 5: input delay 18–26 ms instead of 111–128 ms; presentation delay still 246–264 ms; the snippet printed interleaved: 99 ms, batched: 35 ms.
  • Step 6: Paint about 10 ms for each frame, the drag moved 3–4 ms after the finger, and the snippet printed interleaved: 115 ms, batched: 33 ms. With content-visibility: auto, the check printed 237 of 300 rows rendered.
  • Step 7: no layout shift on either page. The CLS lines said "value":0 for /show.html and /seats.html.

Stretch: in the canvas excerpt, event.offsetX is one of the reads that can force layout. Why does it cost almost nothing in that handler?

Answer

A read forces layout only when the layout is stale. The handler reads offsetX first, before it changes anything, and nothing has changed since the last frame, so the browser answers from the layout it already has.

Cheat sheet

Rendering cost and layout shifts
  1. Main thread: style, layout, pre-paint, paint, layerize, hit test
  2. Compositor: scrolls and draws committed layers without the main thread
  3. Paint and hit testing visit every box unless a parent rules it out
  4. Rows + contain: paint -> a change repaints one row, not the map
  5. content-visibility: auto skips only what is far away (Chromium: 150%)
  6. Read layout before you write; a read after a write forces a layout
  7. Canvas: fast, but one element; build an accessible way to pick a seat
  8. <img width height> + height: auto -> no shift when the picture arrives
  9. Web fonts: preload + optional, or a fallback matched with overrides

Figure 10 is the whole module in one picture: a symptom, the step it points to, and the fix.

[symptom]                     [where to look]               [fix]
drag waits, then jumps   ---> busy main thread at the  ---> make each frame
                              drag's start: paint, hit      cheap: rows and
                              tests                         contain: paint
tap: long input delay    ---> Hit test events          ---> a level the hit
                                                            test can rule out
tap: long presentation   ---> Paint and Layerize after ---> containment, or
                              the handlers                  fewer elements
long script with forced  ---> forcedStyleAndLayout-    ---> read before write
layout                        Duration, Forced reflow
something moved          ---> Layout shifts track,     ---> width and height,
                              culprits insight              reserved space,
                                                            font fallbacks

Figure 10: the symptom names the step; the step names the fix.

Next, in Module 7, a new analytics script and the payment widget make the show page slower. Maya also looks at the 0.8 s of script that still opens the seat map.

Sources