Layout and layout thrashing
Why reading a size after a change makes Chrome lay out at once, how to batch reads and writes, keep layout small with contain: strict, and use ResizeObserver.
- 01Spot a forced layoutTell which reads make Chrome lay out at once, and when the same read costs nothing.
- 02Batch reads and writesTurn a loop that lays out hundreds of times into one that lays out once, and check it in a trace.
- 03Keep layout smallRead a Layout event's root and node count, use contain: strict, and watch sizes with ResizeObserver.
One tap, 375 layouts
Asha is back on Leaf and Kettle's mint tea reviews. Ravi's page still shows all 1,000 of them. Some reviews are long, and Asha has to scroll a lot. So Ravi adds a switch called Short reviews. It folds every long review down to its first two lines.
Asha taps it. For most of a second, nothing happens. Then the reviews fold. Here is what she saw, in real frames from Chrome, and what Chrome did in between:
Here are the main numbers as code:
// Asha's tap on Short reviews, from Chrome's trace.// Times are in milliseconds (ms) after her tap.const tap = { foldedFrame: 826.8, scriptMs: 748, layouts: 375, layoutMs: 628.8 }; console.log(`The folded page appeared at ${tap.foldedFrame} ms.`);console.log(`Ravi's script ran for ${tap.scriptMs} ms.`);console.log(`Inside it, Chrome laid out the page ${tap.layouts} times, for ${tap.layoutMs} ms.`);- Lines 1 and 2 are comments. A millisecond (ms) is a thousandth of a second.
- Line 3 holds what Chrome's trace recorded. A trace is Chrome's detailed record of everything it did, as in lesson 7.2.
- Line 5 prints
The folded page appeared at 826.8 ms.Line 6 printsRavi's script ran for 748 ms. - Line 7 prints
Inside it, Chrome laid out the page 375 times, for 628.8 ms.
Layout is the step where the browser works out the size and place of every box on the page. You met it in lesson 6.3. Chrome keeps a box for each element it shows, and for each piece of text. These boxes are called layout objects. Ravi's page has 6,020 elements and 12,018 layout objects.
Normally Chrome lays out once per frame, after your script has finished. Here it laid out 375 times, inside one script. That took 628.8 ms, most of Asha's wait. So Ravi has three questions. Why 375 times? How does he make it once? And how much of the page does each layout have to touch? This lesson answers all three, with real recordings.
Ravi plans a road trip with a satnav. He adds a stop, then asks how far the next turn is. To answer, the satnav works out the whole route again. He adds another stop and asks again. Ten stops, ten new routes. If he added all ten stops first, the satnav would work out the route once.
- In real life: Adding a stop to the trip
- In JavaScript: Changing the page, like folding a review
- In real life: "How far is the next turn?"
- In JavaScript: Reading a size, like
scrollHeight - In real life: The satnav working out the whole route
- In JavaScript: Chrome laying out the page
- In real life: Adding every stop, then asking once
- In JavaScript: Every change first, then one read
Chrome lays out once per frame, unless a script asks for a size after changing the page. Then it lays out at once. Ask after every change, and Chrome lays out after every change. Read every size first, then change the page, and it lays out once.
How the course recorded it
- The browser: Chrome 157, on a screen the size of Asha's phone: 412 by 823 px. Its processor, the CPU, was slowed 4 times, as in lesson 31.1.
- The page: Ravi's reviews page from lesson 31.1. Each review now also says how many people found it helpful.
- The changes: the opening tap was a real mouse click. The course made every other change 9 times, with JavaScript run in the page, and kept the middle one.
- The times: they come from the course's own computer, so yours will differ. The number of layouts won't.
Which questions make Chrome lay out at once
Lesson 6.3 gave this its name. When a script makes the browser lay out before the frame, web.dev calls it a forced synchronous layout. Synchronous means "now, before your next line of code runs". Chrome's tools call it a forced reflow. Reflow is Firefox's word for layout.
The JavaScript lesson DOM & rendering performance and the system design lesson Layout, paint, and compositing cover the basics. This lesson measures each case in Chrome.
So which questions force it? Think about what the answer is made of. The CSSOM View spec defines offsetWidth as the width of the element's border box. Box sizes are what layout works out. If the page changed since the last layout, the old answer may be wrong. Here is the smallest example:
// One change, then one questionconst ben = document.querySelector("#review-14");ben.style.paddingLeft = "13px";const width = ben.offsetWidth;- Line 1 is a comment. Line 2 finds Ben's review, the one with his photo.
- Line 3 gives it 1 px more padding. That's a change of size.
- Line 4 asks for the review's width. The last layout is out of date, so Chrome must lay out first.
Blink is Chrome's rendering engine: the part that turns HTML and CSS into a page. In its code, offsetWidth starts with one call: update style and layout for this node. A comment beside that call says why: "For all nodes we must have up-to-date style and have performed layout to do any location-based calculation."
Two details matter here:
- Chrome brings the whole document up to date, not only Ben's review.
- It works in order: style first, then layout, and each only if it's out of date. If nothing changed, it does nothing at all.
The course asked 16 questions on Ravi's page. Most came right after a change, in the same script. Paul Irish keeps a long list of questions like these. Read each row across: the question, what changed just before it, and how many Recalculate style and Layout events ran inside the script.
| The question | Just before it | Restyles | Layouts |
|---|---|---|---|
ben.offsetWidth | 1 px more padding | 1 | 1 |
ben.offsetTop | 1 px more padding | 1 | 1 |
ben.clientHeight | 1 px more padding | 1 | 1 |
ben.scrollHeight | 1 px more padding | 1 | 1 |
ben.getBoundingClientRect() | 1 px more padding | 1 | 1 |
getComputedStyle(ben).width | 1 px more padding | 1 | 1 |
ben.innerText | 1 px more padding | 1 | 1 |
window.scrollY | 1 px more padding | 1 | 1 |
document.elementFromPoint(20, 200) | 1 px more padding | 1 | 1 |
getComputedStyle(ben).color | 1 px more padding | 1 | 0 |
ben.offsetWidth | A new colour | 1 | 0 |
ben.textContent | 1 px more padding | 0 | 0 |
ben.style.paddingLeft | 1 px more padding | 0 | 0 |
ben.classList.contains("folded") | 1 px more padding | 0 | 0 |
ben.offsetWidth | 1 px more padding, then the same question | 1 | 1 |
ben.offsetWidth | Nothing yet | 0 | 0 |
Every question about a size or a place laid out: offsetWidth, getBoundingClientRect(), innerText, scrollY and the rest. The layout after Ben's 1 px of padding took 3.1 ms for offsetWidth. That's a lot for one pixel. The section on layout roots shows why.
Four rows are worth a second look:
getComputedStyle(ben).coloronly restyled. A colour doesn't depend on any box's size. Blink lays out for a computed value only when the property depends on layout, likewidth.- After a new colour,
offsetWidthonly restyled too. A colour can't change a width, so the old layout was still right. textContent, a style attribute's value andclassListdid nothing. Their answers are already stored in the elements.- Asked twice,
offsetWidthlaid out once. Asked before the change, it didn't lay out at all.
Why it matters: a read isn't slow by itself. It's slow when a change of size came just before it. Pick a question and see what Chrome did:
ben.style.paddingLeft = "13px";
ben.offsetWidth;113.1 msThe width of Ben's review, border included. Layout works it out.
Read every size first, then change the page
Now Ravi's script makes sense. Here it is:
// Ravi's first version: fold every long review to two linesconst texts = document.querySelectorAll(".review-text");function foldReviews(event) { for (const text of texts) { const long = text.scrollHeight > 48; text.classList.toggle("folded", event.target.checked && long); }}document.querySelector("#short").addEventListener("change", foldReviews);- Line 2 finds the words of all 1,000 reviews.
- Line 3 starts the function. Line 9 runs it each time the Short reviews switch changes.
- Line 5 is a read. A review is long if its words are taller than 48 px: two lines of 24 px.
scrollHeightis the full height of what's inside, even the part a fold hides. - Line 6 is a write. It adds the class
foldedto a long review while the switch is on. That class sets a maximum height of 48 px and hides the rest.
Each fold on line 6 changes the page. Then the loop comes back to line 5 for the next review. The last layout is now out of date, so Chrome lays out the whole page again. One fold, one layout. Many forced layouts in a row are called layout thrashing, as lesson 6.3 showed.
But why 375 and not 1,000? Only 375 reviews were long. A short review isn't folded, so nothing changes, and the next read is free. The recording counted exactly one layout per fold. Here are the first 72 ms after each version of the tap:
A good tailor takes every measurement first and writes them all down. Then she cuts. A tailor who cut one sleeve, then measured the whole customer again, then cut the next piece, would take all day.
- In real life: Taking a measurement
- In JavaScript: Reading a size, like
scrollHeight - In real life: Cutting the cloth
- In JavaScript: Changing the page, like folding a review
- In real life: Measuring the whole customer again after each cut
- In JavaScript: A layout after every fold
- In real life: The page of measurements
- In JavaScript: The array
longin the fix
Ravi's fix works like the good tailor:
// The fix: read every height first, then foldconst texts = document.querySelectorAll(".review-text");function foldReviews(event) { const long = [...texts].map((text) => text.scrollHeight > 48); texts.forEach((text, i) => { text.classList.toggle("folded", event.target.checked && long[i]); });}document.querySelector("#short").addEventListener("change", foldReviews);- Line 4 reads all 1,000 heights into an array called
long. Nothing has changed yet, so Chrome answers each one from the last layout. - Lines 5 to 7 only write. Each review is folded if its entry in
longsays so. - Chrome lays out once, after the script, when it gets the next frame ready.
Doing all the reads first, then all the writes, is called batching. web.dev's advice is to "batch your style reads and do them first". The course tapped each version 9 times:
// Each version of Ravi's script. Middle of 9 taps each.const versions = [ { name: "First version", scriptMs: 694.6, layouts: 375, layoutMs: 582.4 }, { name: "The fix", scriptMs: 4.7, layouts: 1, layoutMs: 11.1 },];for (const v of versions) { console.log(`${v.name}: script ${v.scriptMs} ms, layout ${v.layoutMs} ms, layouts: ${v.layouts}`);}- Lines 3 and 4 hold each version's middle tap: the script's time, the layouts, and their total time.
- Line 7 prints
First version: script 694.6 ms, layout 582.4 ms, layouts: 375andThe fix: script 4.7 ms, layout 11.1 ms, layouts: 1.
The same folds, the same page. The script went from 694.6 ms to 4.7 ms. On Asha's real tap, the folded page appeared at 134.2 ms instead of 826.8 ms. Chrome's Event Timing gave the whole tap 131.9 ms instead of 819.7 ms. Lesson 26.1 showed that INP, roughly a visit's slowest tap or click, is good at 200 ms or less. The first version was four times over. The fix is under.
Notice that the layout didn't disappear. It ran once, after the script, for 12.8 ms. This time 755 of the 12,018 layout objects needed layout, for all 375 folds at once. Why it matters: batching doesn't remove layout. It does it once.
Finding it in DevTools
DevTools points at forced layouts in three places. Lesson 7.3 met the last one:
- Click a purple Layout block inside a script. Its summary has a Function stack: the line of JavaScript that asked. For Asha's tap, it points at the
scrollHeightread, line 5 above. - When a task's forced layouts and restyles add up to 30 ms or more, each one gets a small red triangle. Its warning says "Forced reflow is a likely performance bottleneck".
- The Forced reflow insight names the top function. For Asha's tap:
foldReviews, with 692.6 ms of reflow. Her long animation frame said the same: 697.1 ms of forced style and layout in a frame of 807.1 ms.
One more tip, for when reads and writes live in different parts of your code. web.dev's first example reads a height inside requestAnimationFrame, at the start of a frame. There, the last frame's sizes are known, as long as nothing has changed them since. So run the reads first, then the writes.
Compare both versions, and time them in your own browser:
for (const text of texts) {
const long = text.scrollHeight > 48;
text.classList.toggle("folded", event.target.checked && long);
}694.6 ms375582.4 msnot timed yetEach fold changes the page, and the next review's scrollHeight has to be true, so Chrome lays out after every fold.
How far one change reaches: layout roots and containment
Remember the 3.1 ms for one pixel of padding? Here is a smaller change still. Asha taps Helpful on Ben's review, and the line below it counts up:
const votes = document.querySelector("#review-14 .votes");let count = 12;document.querySelector("#review-14 .helpful").addEventListener("click", () => { count += 1; votes.textContent = `${count} people found this helpful`;});- Line 1 finds the votes line on Ben's review. Line 2 starts the count at 12.
- Line 3 runs the function when Asha taps Helpful.
- Line 4 adds one. Line 5 rewrites the line:
13 people found this helpful.
One line of text changed. Yet Chrome's Layout took 2.9 ms. Click that Layout in DevTools, and its summary shows two lines:
- Nodes that need layout: 8 of 12018. Eight layout objects were marked, out of the page's 12,018.
- Layout root: #document. That's the box Chrome started laying out from.
Here's why. When a box changes, Blink marks it as needing layout. Then it marks its parent, and that parent's parent, all the way up. A taller votes line might make the review taller, and that would move every review below. Blink stops at the first box whose size can't change from inside. That box becomes the layout root. Ravi's page has none on the way up, so the marks climb to the document. web.dev says the same: "Layout is almost always scoped to the entire document."
Train staff move some seats inside one carriage. The carriage is a fixed length, so the train can't get longer. Only that carriage needs checking. If the carriage could stretch, the whole train might change length, and every carriage behind it would move.
- In real life: A carriage of fixed length
- In JavaScript: A box with size containment
- In real life: Moving seats inside it
- In JavaScript: A change inside the box
- In real life: Checking only that carriage
- In JavaScript: Layout starting at that box: the Layout root
- In real life: A carriage that could stretch
- In JavaScript: A box whose size depends on what's inside
CSS has a way to make that promise: the contain property, from the CSS Containment spec. It has two short forms:
contain: strictturns on size, layout, paint and style containment. Size containment means the box is sized as if it were empty. Its contents can't make it bigger.contain: contentturns on layout, paint and style containment, but not size. The spec says layout containment makes the box "totally opaque for layout purposes": nothing outside affects its insides, and nothing inside affects the outside.
The course tried both on the votes line:
/* Every version: the votes line is one line tall */.votes { height: 24px; }/* Version 2 */.votes { contain: content; }/* Version 3 */.votes { contain: strict; }- Line 2 gives every version the same height, 24 px. With size containment, a box needs a size, or it's as tall as an empty box.
- Line 4 is version 2. Line 6 is version 3.
// One vote on Ben's review. Middle of 9 votes each.const versions = [ { contain: "none", root: "#document", nodes: "8 of 12018", ms: 2.9 }, { contain: "content", root: "#document", nodes: "8 of 12018", ms: 2.7 }, { contain: "strict", root: "p.votes", nodes: "2 of 2", ms: 0.088 },];for (const v of versions) { console.log(`contain: ${v.contain}. Root ${v.root}, ${v.nodes} nodes, ${v.ms} ms`);}- Lines 3 to 5 hold each version's Layout after a vote, as DevTools shows it.
- Line 8 prints
contain: none. Root #document, 8 of 12018 nodes, 2.9 msandcontain: content. Root #document, 8 of 12018 nodes, 2.7 ms. Then it printscontain: strict. Root p.votes, 2 of 2 nodes, 0.088 ms.
contain: strict, they stop at the votes line, and layout starts there.With contain: strict, the marks stopped at the votes line. It became the Layout root. Chrome laid out 2 layout objects, the line and its text, in 0.088 ms. Blink's code has the rule: a box with both layout and size containment can be a layout root.
contain: content didn't help at all. Without size containment, the line could still grow. The spec warns about this: invalidation can "percolate further up the tree than desired". Its advice: "Use contain: strict when possible".
There's one more catch. Blink's code says: "In general we can't relayout a flex item independently of its container". The same goes for grid items. A flex container sizes its children together, so one child can't be laid out alone. The course made each review a flex column, with contain: strict still on the votes line. The Layout root went back to #document, and layout took 2.4 ms again.
Why it matters: a fixed-size widget that changes often is a good place for contain: strict. Think of a countdown, a counter, or a live score. Give it a size, and keep it out of flex and grid items. Lesson 31.3 uses containment to skip whole parts of a page.
Try all four versions:
.votes { height: 24px; }#document8 of 120182.9 msChrome marks the votes line and every box above it, up to the document. It lays out from the top.
What makes one layout slow: width, text, flex and grid
Nodes that need layout counts where a change started. It doesn't count the work. The course made two changes that touch every review:
// One change to every review. Middle of 9 each.const changes = [ { change: "title 8 px taller", nodes: 5, ms: 0.59 }, { change: "column 20 px narrower", nodes: 4, ms: 42.8 },];for (const c of changes) { console.log(`${c.change}: ${c.nodes} nodes marked, layout ${c.ms} ms`);}- Line 3 holds the title made 8 px taller. Every review moves down 8 px.
- Line 4 holds the column made 20 px narrower. Every review gets narrower.
- Line 7 prints
title 8 px taller: 5 nodes marked, layout 0.59 msandcolumn 20 px narrower: 4 nodes marked, layout 42.8 ms.
Both changes marked about the same number of nodes. One took about 70 times as long. The difference is what happened inside each review. Blink keeps each box's last layout. When a box gets the same space as before, and nothing inside it changed, Blink can use that layout again. It just places the box. Moving a review down changes its place, not its width. So Chrome could reuse each review's layout.
A narrower column changes every review's width. Then every review has to be laid out again. Every line of its words is broken again: which words fit on line one, which go to line two.
Meera slides the shop's bookcase along the wall. It takes a minute: the books stay where they are. Then she swaps in narrower shelves. Now every book has to be placed again, and some move to the shelf below.
- In real life: Sliding the bookcase along the wall
- In JavaScript: Moving the reviews down: each one's last layout is reused
- In real life: Fitting the books onto narrower shelves
- In JavaScript: A narrower column: every line of text broken again
What about the way the reviews are stacked? The course built the list two more ways:
/* Flex version */#reviews { display: flex; flex-direction: column; gap: 12px; padding-top: 12px; }.review { margin-top: 0; }/* Grid version */#reviews { display: grid; gap: 12px; padding-top: 12px; }.review { margin-top: 0; }- Line 2 stacks the reviews in a flex column, with a 12 px gap. Line 3 drops the old margin, so the page looks the same.
- Line 5 stacks them in a one-column grid, with the same gap.
// The column made narrower. 9 tries each.const lists = [ { display: "block", middle: 42.8, low: 33.7, high: 53.9 }, { display: "flex", middle: 49.6, low: 39.1, high: 56.3 }, { display: "grid", middle: 42, low: 23.3, high: 62.4 },];for (const l of lists) { console.log(`${l.display}: ${l.middle} ms, from ${l.low} to ${l.high}`);}- Lines 3 to 5 hold the middle of 9 tries for each list, and the fastest and slowest.
- Line 8 prints
block: 42.8 ms, from 33.7 to 53.9andflex: 49.6 ms, from 39.1 to 56.3. Then it printsgrid: 42 ms, from 23.3 to 62.4.
The ranges overlap a lot. On this page, there's no clear winner. Why it matters: choose block, flex or grid for the design. To keep layout fast, avoid changing many boxes' widths at once, and remember that flex and grid items can't be layout roots.
Let the browser tell you when a size changes
Ravi adds a small chart above the reviews. It shows how many reviews gave five stars, four stars, and so on. He draws it on a canvas, which holds a fixed number of pixels. If its box gets wider, the browser stretches the old drawing. So the chart must be drawn again whenever the column's width changes. That happens when Asha turns her phone sideways: the column grows from 380 px to 640 px.
const chart = document.querySelector("#chart");function draw(width) { chart.width = width; chart.height = 60; const pen = chart.getContext("2d"); pen.fillStyle = "#2f5d46"; [62, 21, 9, 5, 3].forEach((share, i) => pen.fillRect(0, i * 12, (width * share) / 100, 9));}- Line 1 finds the canvas. Line 2 starts the function that draws it at a given width.
- Lines 3 and 4 size the canvas's drawing area: as wide as the column, 60 px tall.
- Lines 5 to 7 draw five bars, one for each number of stars. Each bar's length is its share of the width.
How does Ravi's code find out that the width changed? His first idea is to check in every frame:
// Check the width in every framelet last = 0;function check() { const width = chart.offsetWidth; if (width !== last) { last = width; draw(width); } requestAnimationFrame(check);}requestAnimationFrame(check);- Line 2 remembers the last width it drew.
- Line 4 reads the chart's width. Lines 5 to 8 draw again if it changed.
- Line 9 asks for
checkto run in the next frame too, withrequestAnimationFrame. Line 11 starts it.
Checking again and again like this is called polling. A gentler version checks ten times a second instead:
// Check the width every 100 mslet last = 0;setInterval(() => { const width = chart.offsetWidth; if (width !== last) { last = width; draw(width); }}, 100);- Lines 3 and 9 run the check every 100 ms with a timer.
- Lines 4 to 8 are the same check as before.
The third way doesn't check at all. A ResizeObserver is an object the browser calls when an element's size changes:
// Let the browser say when the width changesconst watcher = new ResizeObserver(([entry]) => { draw(Math.round(entry.contentBoxSize[0].inlineSize));});watcher.observe(chart);- Line 2 makes the observer. The browser calls its function with a list of entries, one for each element that changed.
- Line 3 takes the new width from the entry.
contentBoxSizeholds the size of the box's content.inlineSizeis its width, for text that runs across the page, like English. - Line 5 starts watching the chart.
The course recorded about 3.5 seconds of each version. About one second in, Asha turns her phone:
// Asha turns her phone. About 3.5 seconds of each version.const versions = [ { way: "every frame", calls: 213, scriptMs: 49.7, oldChart: 0 }, { way: "every 100 ms", calls: 36, scriptMs: 6.1, oldChart: 1 }, { way: "ResizeObserver", calls: 1, scriptMs: 0.91, oldChart: 0 },];for (const v of versions) { console.log(`${v.way}: calls ${v.calls}, script ${v.scriptMs} ms, frames with the old chart ${v.oldChart}`);}- Lines 3 to 5 hold each version's calls, the time they took, and the frames Chrome drew with the old chart.
- Line 8 prints
every frame: calls 213, script 49.7 ms, frames with the old chart 0. Then it printsevery 100 ms: calls 36, script 6.1 ms, frames with the old chart 1. - The last line is
ResizeObserver: calls 1, script 0.91 ms, frames with the old chart 0.
Checking every frame cost 213 calls to catch one new width. Checking every 100 ms cost fewer calls, but it was late. The browser told the page its new size with a resize event. The timer redrew the chart 42.8 ms after that. By then, Chrome had drawn one frame with the old, stretched chart. ResizeObserver ran once, and on time.
What about forced layouts? In this recording, none of the three forced one. Chrome laid out the turned page in its own task first, for 36.9 to 42.3 ms. But a check in requestAnimationFrame runs early. The HTML spec runs animation frame callbacks before it does "Recalculate styles and update layout". So if anything changed since the last frame, like a vote or a fold, line 4 forces that layout inside Ravi's script.
A ResizeObserver runs later. In the HTML spec, the browser lays out, then gathers the size changes, then calls observers, all before it paints. Chrome's trace showed that order: the turn, Chrome's own work, Ravi's callback, then paint. The new width was already worked out, so reading it cost nothing. Drawing changed the canvas, so Chrome laid out again. But only 5 layout objects needed it, and it took 0.14 ms.
Meera is waiting for a parcel of tea. She could walk to the letterbox every few minutes. Most trips find nothing, and a parcel can sit there until her next trip. Or she can wait for the doorbell. It rings only when the parcel comes, and right when it comes.
- In real life: Walking to the letterbox again and again
- In JavaScript: Polling: reading the width in every frame or on a timer
- In real life: Most trips find nothing
- In JavaScript: 212 of the 213 checks found the same width
- In real life: A parcel waits until your next trip
- In JavaScript: A timer that notices late
- In real life: A doorbell that rings when a parcel arrives
- In JavaScript: ResizeObserver, called when the size changes
Why it matters: when your code needs an element's size, let the browser call you. You skip the empty checks, and your code never forces a layout to find out.
Watch a box with both methods, live:
000Both watchers run in your browser. The frame-by-frame check runs whether or not anything changed. ResizeObserver runs once when it starts, then only when the box's size changes.
Which reads lay out the page?
Here is every recorded change in this lesson. Read each row across: what changed, how many layouts ran, where layout started, and the total layout time.
| What changed | Layouts | Layout root | Layout time |
|---|---|---|---|
| Short reviews, Ravi's first version | 375 | #document | 582.4 ms |
| Short reviews, the fix | 1 | #document | 11.1 ms |
| A vote, no containment | 1 | #document | 2.9 ms |
A vote, contain: content | 1 | #document | 2.7 ms |
A vote, contain: strict | 1 | p.votes | 0.088 ms |
A vote, contain: strict on a flex item | 1 | #document | 2.4 ms |
| The title 8 px taller | 1 | #document | 0.59 ms |
| The column narrower, block list | 1 | #document | 42.8 ms |
| The column narrower, flex list | 1 | #document | 49.6 ms |
| The column narrower, grid list | 1 | #document | 42 ms |
Now sort some reads. Ask: does the answer depend on a box's size or place, only on styles, or on neither? Each read comes right after a change of padding unless it says otherwise.
ben.offsetTop, right after a padding changeben.getBoundingClientRect(), right after a padding changegetComputedStyle(ben).width, right after a padding changewindow.scrollY, right after a padding changegetComputedStyle(ben).color, right after a padding changeben.offsetWidth, right after a new colourben.textContent, right after a padding changeben.classList.contains("folded"), right after a padding changeben.offsetWidth, before any change in this task
Sort each read by what Chrome had to do before it could answer.
Common mix-ups
- "Reading offsetWidth is always slow." No. Before any change, or the second time in a row, it laid out nothing. It's slow right after a change of size.
- "Batching makes layout go away." No. The fix still laid out once, for 12.8 ms. It just didn't lay out 375 times.
- "contain: content makes a box a layout root." No. Without size containment, the box can still grow. The vote still laid out from the document.
- "Nodes that need layout tells you how long layout will take." No. It counts where the change started. 4 nodes took 42.8 ms; 8 nodes took 2.9 ms.
- "Flexbox is slower than block layout." No clear difference on Ravi's page. What mattered was how many boxes changed width.
- "Polling is free when nothing changes." No. Checking every frame ran 213 times in about 3.5 seconds, for one new width.
Practice exercises
Answer first, then use the hints.
Which line makes Chrome lay out the page at once?
const ben = document.querySelector("#review-14");
ben.style.color = "rgb(1, 2, 3)";
const words = ben.textContent;
ben.style.paddingLeft = "13px";
const top = ben.offsetTop;Line 5. Line 3's textContent needs no style or layout. Line 4 changes the padding, a size, so line 5's offsetTop makes Chrome restyle and lay out at once.
Another page has 1,000 reviews, and 120 of them are long. How many layouts does Ravi's first version force when Asha turns Short reviews on?
120. The read after each fold lays out. A short review isn't folded, so the read after it finds the layout up to date.
This loop lays out after every name. Which line should move above the loop?
const list = document.querySelector("#reviews");
for (const name of document.querySelectorAll(".review-name")) {
const width = list.offsetWidth;
name.style.maxWidth = `${width - 28}px`;
}const list = document.querySelector("#reviews");
const width = list.offsetWidth;
for (const name of document.querySelectorAll(".review-name")) {
name.style.maxWidth = `${width - 28}px`;
}Line 3. Read once, before the loop, and every write after it changes nothing Chrome has to measure. Chrome lays out once, after the script.
In the one-change, one-question playground, pick ben.getBoundingClientRect(). How long did its layout take, in ms?
About 4.2 ms: one layout of the whole document, after 1 px of padding on Ben's review.
Download the course's trace of Asha's tap on Short reviews, with Ravi's first version. Load it in DevTools' Performance panel. How many nodes needed layout in the first Layout inside foldReviews?
7 of 12018. The first fold marked the review's words, the review and every box above it, up to the document. The next read laid all of that out.
Ravi's callback now sets the chart's height from its width. Which message does the browser report?
const watcher = new ResizeObserver(([entry]) => {
const width = Math.round(entry.contentBoxSize[0].inlineSize);
chart.style.height = `${width / 6}px`;
draw(width);
});
watcher.observe(chart);"ResizeObserver loop completed with undelivered notifications." The chart's new height is a size change at the same depth, so the browser skips it in this frame and reports this error. Size the chart in CSS, or change only things the observer doesn't watch.
Check your understanding
For each question, ask three things: what changed, what the script asked for, and where Chrome had to start laying out.
Question 1 of 7In Ravi's first version, why did reading
text.scrollHeightmake Chrome lay out the page?Choose an answer to see the explanation.
Question 2 of 7What does the second line of the comparison print?
Read the code, then predict// Each version of Ravi's script. Middle of 9 taps each. const versions = [ { name: "First version", scriptMs: 694.6, layouts: 375, layoutMs: 582.4 }, { name: "The fix", scriptMs: 4.7, layouts: 1, layoutMs: 11.1 }, ]; for (const v of versions) { console.log(`${v.name}: script ${v.scriptMs} ms, layout ${v.layoutMs} ms, layouts: ${v.layouts}`); }Choose an answer to see the explanation.
Question 3 of 7Right after Ben's review gets 1 px more padding, which question makes Chrome restyle but not lay out?
Choose an answer to see the explanation.
Question 4 of 7With
contain: contenton the votes line, a vote still made Chrome lay out from the document. Why?Choose an answer to see the explanation.
Question 5 of 7Ravi puts
contain: stricton the votes line, and makes each review a flex column. What's the Layout root after a vote?Choose an answer to see the explanation.
Question 6 of 7Why did making the column 20 px narrower cost so much more layout than making the title 8 px taller?
Choose an answer to see the explanation.
Question 7 of 7When does Chrome run a ResizeObserver callback?
Choose an answer to see the explanation.
Key takeaways
- Chrome lays out once per frame, unless a script asks for a size after changing the page. Then it lays out the whole document at once.
- A read only forces layout when something changed since the last layout. Before any change, or the second time, it's free.
- Read every size first, then change the page. Ravi's 375 layouts became 1.
- A change marks every box up to a layout root, usually the document. contain: strict makes a fixed-size box a root, unless it's a flex or grid item.
- A change of width breaks every line of text again. A change of place reuses the last layout.
- To follow a size, use ResizeObserver. It runs after layout and before paint, and only when the size changed.
Remember the one-liner.
Measure first, then change, and let the browser tell you when sizes move.
Sources
The facts on this page come from these specs, docs and source files:
- Avoid large, complex layouts and layout thrashing, web.dev.
- CSSOM View Module: offsetWidth and the other box sizes, W3C.
- element.cc: offsetWidth lays out first, Chromium source.
- document.cc: up-to-date style and layout for any location-based calculation, Chromium source.
- local_frame_view.cc: style first, then layout only if needed, Chromium source.
- css_computed_style_declaration.cc: getComputedStyle and layout, Chromium source.
- What forces layout / reflow, Paul Irish.
- inspector_trace_events.cc: what a Layout event records, Chromium source.
- TimelineUIUtils.ts: Nodes that need layout and Layout root, Chrome DevTools source.
- WarningsHandler.ts: when a forced reflow gets a warning, Chrome DevTools source.
- Forced reflow insight, Chrome for Developers.
- layout_object.cc: marking boxes for layout, and layout roots, Chromium source.
- CSS Containment Module Level 2, W3C.
- layout_utils.cc: when a box's last layout can be used again, Chromium source.
- HTML Standard: update the rendering, WHATWG.
- Resize Observer, W3C.
- local_frame_view.cc: resize observations after layout, before paint, Chromium source.
Coming next: DOM size. A big page makes every style and layout slower. You'll measure it, and let Chrome skip the parts nobody can see.