Layout Thrashing

How interleaving DOM reads and writes forces the browser to repeatedly recalculate layout synchronously.

Internet6 min readConcept 33 of 35

What it is

Layout Thrashing (also known as Forced Synchronous Layout) occurs when JavaScript repeatedly reads from and writes to the DOM in a sequence that forces the browser to calculate the page layout synchronously multiple times.

Normally, browsers batch style and layout changes asynchronously until the end of the frame. But if a script modifies an element's style (a write) and immediately requests a geometric property (a read), the browser must pause JavaScript execution and recalculate the layout instantly to return the accurate value.

Why it matters

Layout thrashing is a primary cause of performance bottlenecks on the web.

Forced synchronous layouts block the main thread, leading to dropped frames, visual 'jank' (stuttering animations or scrolling), and high CPU spikes.

To achieve a smooth 60 frames per second (FPS), a browser only has ~16.6 milliseconds to complete the rendering pipeline. Layout thrashing easily blows past this budget.

How it works

The rendering pipeline flows: JavaScript -> Style -> Layout -> Paint -> Composite.

When JavaScript modifies a style, the browser invalidates the layout tree but waits to recalculate it. If JavaScript then asks for a layout-dependent property like offsetWidth or scrollTop, the browser is forced to immediately run the Style and Layout phases.

If this read/write cycle is placed inside a loop, it 'thrashes' the layout engine repeatedly within a single task.

Try it

Experience the Factory Assembly Line. See what happens when a manager asks for measurements and gives orders interleaved, versus batching them!

Interleaved (Bad)
for (let box of boxes) {
  // READ
  const w = box.offsetWidth; 
  // WRITE
  box.style.width = w + 'px';
}
Batched (Good)
// READ ALL
const widths = boxes.map(b => b.offsetWidth);
// WRITE ALL
boxes.forEach((b, i) => {
  b.style.width = widths[i] + 'px';
});
Factory Assembly Line
Cost:0ms
Select a code strategy above to start packing boxes.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the primary cause of layout thrashing?
  2. 2Which of the following JavaScript properties will typically trigger a forced synchronous layout if called immediately after modifying DOM styles?
  3. 3How can you prevent layout thrashing when updating multiple elements?

Remember this

  • Writes invalidate layout. Reads force layout calculation if layout is invalid.
  • Do not read geometry immediately after writing a style.
  • Batch all reads together, followed by all writes.

Done with this concept?

Mark it complete to track your progress. No login needed.