completefrontend
Open lab My progress
THE WEB PERFORMANCE FIELD GUIDE

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.

By the end, you can
  • 01
    Spot a forced layoutTell which reads make Chrome lay out at once, and when the same read costs nothing.
  • 02
    Batch reads and writesTurn a loop that lays out hundreds of times into one that lays out once, and check it in a trace.
  • 03
    Keep 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:

Two real frames of Asha's screen on Ravi's reviews page, cut to their top part. Just before her tap on Short reviews, the long reviews show all their lines. 826.8 ms after her tap, they're folded to two lines. Below, the main thread after the tap, to scale: Ravi's script from 5.4 ms to 753.4 ms, with 375 layouts inside it taking 628.8 ms, then pre-paint, paint and commit until 815.8 ms.Just before her tap826.8 ms after her tapRavi's reviews page with Short reviews off: Asha's and Ravi's reviews show all their lines.The same page with Short reviews on: the long reviews are folded to two lines.foldReviews: 748 ms, 375 layouts insidetap, 0 msfolded frame, 826.8 mspre-paint, paint, commit
Real frames from the course's recording in Chrome, cut to the top of Asha's screen. Below them, what the main thread did after her tap, to scale. Almost all of it was Ravi's script, and most of the script was layout.

Here are the main numbers as code:

Asha's tap on Short reviewsPop out in the code editor (opens in a new tab)JavaScript
// 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 prints Ravi'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.

Real-life analogyA satnav that works out the route again

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

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 questionJavaScript
// 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.

What each question made Chrome do
The questionJust before itRestylesLayouts
ben.offsetWidth1 px more padding11
ben.offsetTop1 px more padding11
ben.clientHeight1 px more padding11
ben.scrollHeight1 px more padding11
ben.getBoundingClientRect()1 px more padding11
getComputedStyle(ben).width1 px more padding11
ben.innerText1 px more padding11
window.scrollY1 px more padding11
document.elementFromPoint(20, 200)1 px more padding11
getComputedStyle(ben).color1 px more padding10
ben.offsetWidthA new colour10
ben.textContent1 px more padding00
ben.style.paddingLeft1 px more padding00
ben.classList.contains("folded")1 px more padding00
ben.offsetWidth1 px more padding, then the same question11
ben.offsetWidthNothing yet00

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).color only 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, like width.
  • After a new colour, offsetWidth only restyled too. A colour can't change a width, so the old layout was still right.
  • textContent, a style attribute's value and classList did nothing. Their answers are already stored in the elements.
  • Asked twice, offsetWidth laid 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:

Playground: one change, one question
The change and the questionJavaScript
ben.style.paddingLeft = "13px";
ben.offsetWidth;
ben.offsetWidthInside the script
Recalculate style events1
Layout events1
Layout time3.1 ms
Try it yourself
Chrome laid out at once

The width of Ben's review, border included. Layout works it out.

Recorded in Chrome 157 with the CPU 4 times slower, on Ravi's page with 1,000 reviews. Each question was asked 5 times, each time in its own task right after the change shown. The times are the middle of the 5.

Read every size first, then change the page

Now Ravi's script makes sense. Here it is:

Ravi's first versionJavaScript
// 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. scrollHeight is the full height of what's inside, even the part a fold hides.
  • Line 6 is a write. It adds the class folded to 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:

The first 72 ms after Asha's tap, to scale. Top, Ravi's first version: his script starts at 5.4 ms, and 30 layouts follow one another inside it, of 375 in all. Bottom, the fix: the script runs for 7.6 ms with no layout, then Chrome restyles the folded reviews and lays out once, for 12.8 ms.Ravi's first version: 30 of its 375 layoutsThe fix: every read first, then one layoutscript, 7.6 msRecalculate styleLayout, 12.8 mstap, 0 ms72 ms
Shaded: Layout. Each shaded block on the top row is one forced layout inside Ravi's first script, and it keeps going long past this picture. The fix lays out once, after its script.
Real-life analogyA tailor who measures before cutting

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 long in the fix

Ravi's fix works like the good tailor:

The fixJavaScript
// 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 long says 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:

Both versions, timedPop out in the code editor (opens in a new tab)JavaScript
// 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: 375 and The 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 scrollHeight read, 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:

Playground: fold the reviews
Ravi's scriptJavaScript
for (const text of texts) {
  const long = text.scrollHeight > 48;
  text.classList.toggle("folded", event.target.checked && long);
}
Ravi's first versionOne tap
Script, in Chrome694.6 ms
Layouts, in Chrome375
Layout time, in Chrome582.4 ms
Script, in your browsernot timed yet
Try it yourself
375 layouts for one tap

Each fold changes the page, and the next review's scrollHeight has to be true, so Chrome lays out after every fold.

Recorded in Chrome 157 with the CPU 4 times slower: the middle of 9 taps. "Time it" loads the same page below and taps Short reviews 3 times in your browser, timing Ravi's script each time. Your numbers depend on your computer.

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:

One more voteJavaScript
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."

Real-life analogyMoving seats in a train carriage

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: strict turns 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: content turns 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:

The votes line, three waysCSS
/* 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, three versionsPop out in the code editor (opens in a new tab)JavaScript
// 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 ms and contain: content. Root #document, 8 of 12018 nodes, 2.7 ms. Then it prints contain: strict. Root p.votes, 2 of 2 nodes, 0.088 ms.
The boxes from the document down to the votes line on Ben's review, after a vote. With no containment, every box on the path needs layout, and the Layout root is the document: 8 of 12,018 layout objects. With contain: strict on the votes line, only the line and its text need layout, and the line is the Layout root: 2 of 2.No containment.votes { contain: strict }#documentLayout roothtmlbodymainul#reviewsli: Ben's reviewp.votesits text#documenthtmlbodymainul#reviewsli: Ben's reviewp.votesLayout rootits text8 of 12,018 need layout2 of 2 need layout
Shaded: the boxes Chrome marked as needing layout after one vote. Without containment, the marks climb to the document. With 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:

Playground: where layout starts
The votes line's rulesCSS
.votes { height: 24px; }
No containmentOne vote
Layout root#document
Nodes that need layout8 of 12018
Layout time2.9 ms
Try it yourself
Layout root: #document

Chrome marks the votes line and every box above it, up to the document. It lays out from the top.

Recorded in Chrome 157 with the CPU 4 times slower: the Layout event after a vote on Ben's review, the middle of 9 votes. Nodes that need layout and Layout root are the two lines DevTools shows in a Layout event's summary.

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:

Two changes to every reviewPop out in the code editor (opens in a new tab)JavaScript
// 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 ms and column 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.

Real-life analogySliding a bookcase, or reshelving it

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:

The same list as flex and as gridCSS
/* 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 narrower column, three listsPop out in the code editor (opens in a new tab)JavaScript
// 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.9 and flex: 49.6 ms, from 39.1 to 56.3. Then it prints grid: 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.

Drawing the chartJavaScript
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:

Checking in every frameJavaScript
// 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 check to run in the next frame too, with requestAnimationFrame. Line 11 starts it.

Checking again and again like this is called polling. A gentler version checks ten times a second instead:

Checking every 100 msJavaScript
// 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:

Letting the browser callJavaScript
// 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. contentBoxSize holds the size of the box's content. inlineSize is 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 phonePop out in the code editor (opens in a new tab)JavaScript
// 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 prints every 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.
3.56 seconds of Ravi's page while Asha turns her phone, about 1 seconds in. Checking the width in every frame ran 213 times. Checking every 100 ms ran 36 times. ResizeObserver ran once, just after the turn.Asha turns her phoneCheck in every frame: 213 callsCheck every 100 ms: 36 callsResizeObserver: 1 call0 s3.56 s
Each mark is one call of Ravi's code, to scale. Only one call in each row found a new width: the one just after Asha turned her phone.

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.

Real-life analogyA letterbox, or a doorbell

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:

Playground: who notices a new width?
The watched box100% wide
Ravi's chart
Checks in every frame0
…that found a new width0
ResizeObserver calls0
Try it yourself
Press Watch, then move the slider a few times

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

This runs live in your browser, so the counts depend on your screen's frame rate and on how often you move the slider.

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.

Every change, side by side
What changedLayoutsLayout rootLayout time
Short reviews, Ravi's first version375#document582.4 ms
Short reviews, the fix1#document11.1 ms
A vote, no containment1#document2.9 ms
A vote, contain: content1#document2.7 ms
A vote, contain: strict1p.votes0.088 ms
A vote, contain: strict on a flex item1#document2.4 ms
The title 8 px taller1#document0.59 ms
The column narrower, block list1#document42.8 ms
The column narrower, flex list1#document49.6 ms
The column narrower, grid list1#document42 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.

Which reads lay out the page?
  • ben.offsetTop, right after a padding change
  • ben.getBoundingClientRect(), right after a padding change
  • getComputedStyle(ben).width, right after a padding change
  • window.scrollY, right after a padding change
  • getComputedStyle(ben).color, right after a padding change
  • ben.offsetWidth, right after a new colour
  • ben.textContent, right after a padding change
  • ben.classList.contains("folded"), right after a padding change
  • ben.offsetWidth, before any change in this task
Try it yourself
0 of 9 correct

Sort each read by what Chrome had to do before it could answer.

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

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.

Exercise 1 · Warm-upWhich line lays out?

Which line makes Chrome lay out the page at once?

Starter codePop out in the code editor (opens in a new tab)JavaScript
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;

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

    Exercise 2 · Warm-upFewer long reviews

    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?

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

      Exercise 3 · PracticeMove one line

      This loop lays out after every name. Which line should move above the loop?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const list = document.querySelector("#reviews");
      for (const name of document.querySelectorAll(".review-name")) {
        const width = list.offsetWidth;
        name.style.maxWidth = `${width - 28}px`;
      }

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

        Exercise 4 · PracticeA box's place and size

        In the one-change, one-question playground, pick ben.getBoundingClientRect(). How long did its layout take, in ms?

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

          Exercise 5 · ChallengeThe first forced layout

          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?

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

            Exercise 6 · ChallengeA chart that changes its own size

            Ravi's callback now sets the chart's height from its width. Which message does the browser report?

            Starter codePop out in the code editor (opens in a new tab)JavaScript
            const watcher = new ResizeObserver(([entry]) => {
              const width = Math.round(entry.contentBoxSize[0].inlineSize);
              chart.style.height = `${width / 6}px`;
              draw(width);
            });
            watcher.observe(chart);

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

              Check your understanding

              For each question, ask three things: what changed, what the script asked for, and where Chrome had to start laying out.

              The layout quiz · 7 questionsScore: first tries count
              1. Question 1 of 7In Ravi's first version, why did reading text.scrollHeight make Chrome lay out the page?

                Choose an answer to see the explanation.

              2. Question 2 of 7What does the second line of the comparison print?

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

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

              4. Question 4 of 7With contain: content on the votes line, a vote still made Chrome lay out from the document. Why?

                Choose an answer to see the explanation.

              5. Question 5 of 7Ravi puts contain: strict on 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.

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

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

              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.

              CompleteFrontend Clear concepts. Working examples.