# Layout Thrashing

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

Subject: Internet | Lesson 33 of 35 | 6 min read
Interactive lesson: https://codewithanimation.in/internet/layout-thrashing
Previous: [Script Loading Strategies](https://codewithanimation.in/internet/script-loading-strategies.md) | Next: [Repaint Triggers](https://codewithanimation.in/internet/repaint-triggers.md)

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

## Common mistake: The Read/Write Loop

A classic mistake is iterating through an array of elements, reading their `offsetHeight`, and immediately applying a new `height` based on that measurement within the same loop.

This interleaves reads and writes, triggering a forced synchronous layout on *every single iteration* of the loop, rather than just once.

## Tip: Pro tip

**Batch your reads, then batch your writes.**

Always perform all your DOM measurements (reads) first and store them in variables. Then, perform all your DOM mutations (writes) sequentially.

Use libraries like `fastdom` to manage read/write boundaries automatically.

## Try it: Try it

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

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/internet/layout-thrashing

## Check yourself

### Question 1

What is the primary cause of layout thrashing?

- A. Having too many deeply nested elements in the DOM tree.
- B. Interleaving DOM reads and DOM writes in a way that forces the browser to calculate layout synchronously.
- C. Using too many CSS animations at the same time.
- D. Loading large external stylesheets that block rendering.

Correct answer: B

Layout thrashing happens when JavaScript repeatedly writes to the DOM and then reads geometric properties, forcing instant recalculation.

- Why not A: While a massive DOM tree makes layout slower, thrashing specifically refers to the forced, synchronous recalculation cycle.
- Why not C: CSS animations usually avoid layout completely and run on the GPU.
- Why not D: This is a render-blocking resource issue, not layout thrashing.

### Question 2

Which of the following JavaScript properties will typically trigger a forced synchronous layout if called immediately after modifying DOM styles?

- A. element.id
- B. element.offsetWidth
- C. element.style.color
- D. element.dataset

Correct answer: B

Properties that return geometric or scroll information-like offsetWidth, clientHeight, and scrollTop-require an up-to-date layout tree.

- Why not A: Reading an ID is just accessing a string property.
- Why not C: Reading an inline style property doesn't require geometry.
- Why not D: Data attributes do not require rendering calculations to be accessed.

### Question 3

How can you prevent layout thrashing when updating multiple elements?

- A. Use setTimeout() for every DOM mutation.
- B. Force a reflow manually before starting the loop.
- C. Apply changes using !important in CSS.
- D. Read all necessary layout properties first, store them, and then perform all DOM style updates together.

Correct answer: D

The golden rule is 'batch your reads, then batch your writes'. This allows the browser to calculate layout once for the reads, and invalidate it cleanly during writes.

- Why not A: This doesn't guarantee reads and writes won't be interleaved when callbacks fire.
- Why not B: You cannot 'lock' the browser's layout.
- Why not C: CSS specificity has no impact on JS layout thrashing.

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