Part 01 · How the Browser Works

Reflow vs Repaint vs Composite-Only

ReflowRepainttransformLayout thrashing

Changing width, color or transform costs very different amounts. Which CSS changes trigger which step, and how reading and writing layout in a loop thrashes it.

⏱ 6 min · Station 7 of 125

The problem

ShopLite's listing page makes every product image box 3/4 as tall as it is wide. A developer writes the obvious loop: for each card, read its width, set its height. With 60 cards nobody notices. Then the "show 1,000 products" option ships, and on a phone the page freezes for almost four seconds after every resize.

The loop does 1,000 multiplications. The time goes somewhere else: into layout, which the loop forces the browser to run 1,000 times.

The idea

Changes to the page cost one of three things:

  • Reflow (layout): sizes or positions changed, so boxes must be measured again. The most expensive.
  • Repaint: only how something looks changed (colour, shadow), so pixels are redrawn, but nothing moves.
  • Composite-only: a layer is moved or faded (transform, opacity). Cheapest; the main thread may not be involved at all.

Normally the browser is lazy: it marks layout as "dirty" and does it once, right before the next frame. But if your code reads a geometry value (like offsetWidth) while layout is dirty, the browser must do layout right now to give you a correct answer. That's a forced synchronous layout. Doing it in a loop, write-read-write-read, is layout thrashing.

How it works

  1. Write: card.style.height = "150px". The browser doesn't lay anything out yet; it marks the tree dirty and moves on. Cheap.
  2. Read: card.offsetWidth. The answer depends on layout, and layout is dirty, so the browser stops your script, recalculates style and runs layout for the whole affected area, then returns the number.
  3. Write again to the next card: dirty again.
  4. Read again: layout again. With 1,000 cards that's 1,000 full layouts inside one task.
  5. Batched version: read all 1,000 widths first (one layout at most, often zero because layout is already clean), then write all 1,000 heights (just marking dirty). Layout runs once, before the next frame.

Reads that force layout include offsetWidth/Height/Top/Left, clientWidth/Height, scrollTop/scrollHeight, getBoundingClientRect(), getComputedStyle() (for layout values), innerText, and focus(). Writes that dirty layout include any geometry style (width, height, top, margin, font-size), adding or removing elements, and changing text.

Predict first

1,000 cards, CPU 4x slower. Version A reads each card's width and immediately sets its height. Version B reads all widths, then sets all heights. How do they compare?

Visual

interleaved: read, write, read, writebatched: all reads, then all writesreadwritelayoutreadwritelayoutreadwritelayoutreadwritelayoutreadreadreadreadreadreadwritewritewritewritewritewrite1 layout, next frameeach read after a write: layout must run NOW to give a fresh answer1,000 cards: 1,000 layouts, 3,911 ms (4x CPU)reads share one clean layout, writes just mark it dirty: 5 ms
Top: interleaved reads and writes force a layout after every write. Bottom: all reads, then all writes, and a single layout later.

Reflow, repaint, composite

Reflow (layout)RepaintComposite-only
Caused bygeometry, DOM, text, font changescolour, background, shadow, outlinetransform, opacity
Work donelayout + paint + compositepaint + compositecomposite
Scopecan spread to parents, siblings, childrenthe changed areaone layer
Can be forced mid-script?yes, by reading geometryno (paint waits for the frame)no
Cost with 1,000 elements, 4x CPU3911 ms when forced 1,000 timesa few ms~0 on the main thread

See it live

Measured on an Intel i3-10110U laptop (4 threads), 7 GB RAM, Ubuntu 26.04, Chrome 151 headless via Playwright 1.64.1, CPU throttled 4x, the lab in Docker on the same machine.

thrash.html renders 1,000 cards and offers the two versions, plus a reset() so every run starts from the same state:

<!doctype html>
<html>
<head>
  <title>layout thrashing</title>
  <style>
    body { font-family: system-ui; }
    .card { display: inline-block; width: 30%; margin: 4px; padding: 8px; border: 1px solid #ddd; }
  </style>
</head>
<body>
  <div id="grid"></div>
  <script>
    const grid = document.getElementById("grid");
    for (let i = 1; i <= 1000; i++) grid.insertAdjacentHTML("beforeend", `<div class="card">Product ${i}</div>`);
    const cards = [...grid.children];

    // Goal: make every card's image area 3/4 of its width.
    // Interleaved: read a width, write a height, read the next width... each read after a write
    // forces the browser to redo layout right now.
    window.interleaved = () => {
      const t = performance.now();
      for (const c of cards) c.style.height = c.offsetWidth * 0.75 + "px";
      return performance.now() - t;
    };
    // Batched: read every width first, then write every height. Layout runs once.
    window.batched = () => {
      const t = performance.now();
      const widths = cards.map((c) => c.offsetWidth);
      cards.forEach((c, i) => (c.style.height = widths[i] * 0.75 + "px"));
      return performance.now() - t;
    };
    // Reset so the next run starts from the same state.
    window.reset = () => {
      for (const c of cards) c.style.height = "";
      return grid.offsetHeight;
    };
  </script>
</body>
</html>

tools/thrash.mjs times each version 5 times (median), then records a trace of one run plus the next frame and counts the Layout events:

// node thrash.mjs: set the height of 1,000 cards from their width, two ways, CPU throttled 4x.
import { open, trace, mainThreadSummary, WEB, ms } from "./lib.mjs";

const { browser, page } = await open({ cpu: 4 });
await page.goto(`${WEB}/x/thrash.html`, { waitUntil: "load" });
console.log("approach       time (median of 5)   layouts (run + next frame)");
for (const fn of ["interleaved", "batched"]) {
  const times = [];
  for (let i = 0; i < 5; i++) {
    await page.evaluate(() => window.reset());
    times.push(await page.evaluate((f) => window[f](), fn));
  }
  await page.evaluate(() => window.reset());
  // trace the run plus the next frame, so a layout the browser does later is counted too
  const events = await trace(browser, page, () =>
    page.evaluate((f) => (window[f](), new Promise((r) => requestAnimationFrame(() => setTimeout(r, 50)))), fn),
  );
  const s = mainThreadSummary(events, ["Layout"]);
  times.sort((a, b) => a - b);
  console.log(`${fn.padEnd(14)} ${ms(times[2]).padStart(19)} ${String(s.Layout.count).padStart(24)}`);
}
await browser.close();
approach       time (median of 5)   layouts (run + next frame)
interleaved                3911 ms                     1000
batched                       5 ms                        1

Reading it:

  • Interleaved: 3911 ms and 1000 layouts. One layout per card. Each one had to lay out the whole grid, because changing a card's height can move every card after it.
  • Batched: 5 ms and 1 layout, the normal one the browser does before the next frame. The reads didn't need any layout of their own: the page was already laid out when they ran.
  • Same result on screen, about 780x faster. Nothing about the work changed except the order of reads and writes.

In real apps

  • Group DOM reads and writes. Read everything you need first, then write. Libraries like fastdom formalise this; React's commit phase and most frameworks batch DOM writes for you, but your useLayoutEffect code and imperative widgets don't get that for free.
  • Use CSS instead of measuring. aspect-ratio: 4 / 3 gives ShopLite's image boxes the right height with no JavaScript at all.
  • Use observers instead of polling. ResizeObserver tells you when a size changed, and IntersectionObserver when something becomes visible, both without forcing layout in your code.
  • Find it in traces. DevTools marks forced layouts with a warning on the Layout event, plus the line of JavaScript that triggered it (Lab: Reading a Performance Trace).

What goes wrong in production

  • Measuring in a loop inside a list, a masonry grid or a "fit text to box" helper: invisible with 20 items, seconds with 1,000.
  • Scroll handlers that read scrollTop and write styles on each event: forced layout on every scroll tick.
  • Third-party widgets that call getBoundingClientRect() on many elements during load.
  • Animation code that reads offsetLeft to compute the next position each frame, turning a cheap transform animation back into a layout-per-frame one.

Key takeaway

Writes are lazy, reads of geometry are not: a read after a write forces layout immediately. Batch all reads before all writes, prefer CSS (aspect-ratio, flex, grid) over measuring, and keep geometry reads out of loops and scroll handlers.

Practice

Keep the interleaved loop exactly as it is (read offsetWidth, then write), but write c.style.color instead of c.style.height. Predict the time for 1,000 cards on the 4x slower CPU. Then try it in the browser console on thrash.html or in a copy of thrash.mjs.

Answer

It's fast: we measured 7 ms (median of 5). Changing color dirties style and paint, but not layout. The next offsetWidth read finds layout still clean, so the browser only has to recalculate the one changed style, not lay out the grid. Layout thrashing needs both halves: a write that invalidates layout and a read that needs it.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →