Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท CSS and Rendering

Layout Thrashing and Reflow

Understand forced synchronous layout, why mixing DOM reads and writes in a loop is slow, and how to batch with requestAnimationFrame, fragments and ResizeObserver.

Normally the browser delays layout until it needs to paint, so many style changes are batched into one calculation. But if your JavaScript changes a style and then reads a layout value such as offsetHeight, the browser must calculate layout right now to answer. That is a forced synchronous layout (or forced reflow). Do it once and nobody notices. Do it in a loop that alternates writes and reads, and you get layout thrashing: one full layout per iteration.

Which reads force layout

Reading these properties or calling these methods asks the browser for up-to-date geometry:

  • offsetWidth, offsetHeight, offsetTop, offsetLeft
  • clientWidth, clientHeight, scrollTop, scrollHeight
  • getBoundingClientRect(), getComputedStyle(el).height (and similar)
  • innerWidth, innerHeight on the window

If the DOM or styles changed since the last layout, the browser stops and recalculates before returning the value.

The thrashing pattern

JavaScript
// Slow: each iteration writes, then reads, forcing layout every time
for (const box of boxes) {
  box.style.width = container.offsetWidth / 2 + "px"; // read (forces layout), then write
}

After the first write, the layout is invalid. The next container.offsetWidth read forces a full recalculation, then the write invalidates it again. With 1,000 boxes you pay for 1,000 layouts.

flowchart LR
  W1["write"] --> R1["read: forces layout"] --> W2["write"] --> R2["read: forces layout"] --> W3["write"]

Alternating writes and reads defeats the browser's batching.

The fix: read first, write after

Group all reads together, then all writes. The browser calculates layout once.

JavaScript
// Fast: one read, many writes
const half = container.offsetWidth / 2;   // read once
for (const box of boxes) {
  box.style.width = half + "px";          // writes only
}

Measure the difference

Thrashing versus batching

The exact numbers depend on your machine, but the thrashing version is typically many times slower.

Batch DOM writes

Building a list by appending to the live DOM one element at a time can trigger style recalculation repeatedly. Build off-screen and insert once:

JavaScript
const fragment = document.createDocumentFragment();
for (const text of items) {
  const li = document.createElement("li");
  li.textContent = text;
  fragment.append(li);
}
list.append(fragment); // one insertion

innerHTML with a single string, or replaceChildren(...nodes), also does one big update.

Use requestAnimationFrame to schedule writes

Do your reads in the event handler and put the writes in requestAnimationFrame, so they happen right before the browser paints:

JavaScript
element.addEventListener("pointermove", (event) => {
  const x = event.clientX;                      // read-like data from the event
  requestAnimationFrame(() => {
    marker.style.transform = `translateX(${x}px)`;   // write
  });
});

Prefer observers over polling geometry

Do not measure in scroll handlers if an observer can tell you:

  • IntersectionObserver tells you when an element enters the viewport (lazy loading, infinite scroll, play-on-visible).
  • ResizeObserver tells you when an element's size changes, without forcing layout from your code.
IntersectionObserver instead of scroll math

No getBoundingClientRect() in a scroll handler, no forced layout.

Other reflow triggers to know

  • Changing fonts, text content or the number of lines of text.
  • Adding or removing elements near the top of a big page.
  • Images without width and height that load late (layout shift).
  • Using getComputedStyle right after changing a class.

Use the Performance panel: forced reflows show up as a purple "Layout" block with a warning triangle and a stack trace pointing at the read that caused it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is layout thrashing?

    Each read after a write forces a synchronous layout instead of letting the browser batch.
  2. 2. Which of these reads can force layout?

    Geometry properties such as offsetHeight require up-to-date layout.
  3. 3. How do you fix a loop that reads container width and writes box widths in each iteration?

    Grouping reads before writes lets the browser compute layout once.
  4. 4. Which API lets you react to an element entering the viewport without measuring on scroll?

    IntersectionObserver reports visibility changes efficiently.

Summary

  • Reading geometry after changing styles forces a synchronous layout.
  • Alternating reads and writes in a loop causes layout thrashing.
  • Batch reads, then batch writes; build DOM in fragments; schedule writes with rAF.
  • Prefer IntersectionObserver and ResizeObserver to manual measuring.

Next: Containment, content-visibility and Smooth Animations