Course contentsShow
← Web Development
Lesson 2062 of 2,98238. JavaScript Performance in the BrowserFree lesson

The Cost of Layout Thrashing

How interleaving DOM reads and writes forces synchronous layout recalculation and blocks the thread.

The Cost of Layout Thrashing

You'll learn why alternating between reading and writing DOM properties causes severe performance penalties that can freeze your interface.

What Is Layout Thrashing?

Layout thrashing (also called forced synchronous layout) happens when you read a layout property (like offsetHeight or getBoundingClientRect()) immediately after writing to the DOM. The browser hasn't had a chance to calculate the new layout yet, so it must stop everything and recalculate styles and layout right now to give you an accurate answer.

Think of it like constantly asking "Are we there yet?" during a road trip. Each time you ask, the driver must stop the car, check the map, calculate the remaining distance, and only then resume driving. The trip takes far longer than necessary.

The Interleaving Problem

// BAD: Read-write-read-write pattern
elements.forEach(el => {
  const height = el.offsetHeight; // READ (forces layout)
  el.style.height = height + 10 + 'px'; // WRITE
  // Next iteration triggers another forced layout!
});

// GOOD: Batch reads, then batch writes
const heights = elements.map(el => el.offsetHeight); // All READS first
elements.forEach((el, i) => {
  el.style.height = heights[i] + 10 + 'px'; // Then all WRITES
});

When you interleave reads and writes, each read forces the browser to recalculate layout synchronously—blocking the main thread for potentially tens of milliseconds per cycle. In a loop, this compounds catastrophically.

Why It Blocks

The browser optimizes by batching layout calculations. But when you read layout properties, it can't wait—it must give you accurate data now, even if that means halting JavaScript execution to recalculate.

Key Takeaway: Separate DOM reads from DOM writes to avoid forcing synchronous layout calculations that block the main thread and destroy performance.