Course contentsShow
← Web Development
Lesson 547 of 2,9829. CSS Transitions and AnimationsFree lesson

Avoiding Layout Thrashing

Batch DOM reads and writes to prevent forced synchronous layout during animations.

Avoiding Layout Thrashing

What you'll learn: How to structure your animation code so the browser doesn't wastefully recalculate layout over and over again.


The Core Problem

Layout thrashing (also called "forced synchronous layout") happens when you repeatedly read and write DOM properties in the wrong order during animations. Here's the issue: when you write a style that changes layout (like width or top), the browser marks the layout as "dirty." When you then immediately read a layout property (like offsetWidth or getBoundingClientRect()), you force the browser to stop everything and recalculate layout right then—even mid-frame.

If you alternate read-write-read-write many times in a loop, the browser recalculates layout every single time. This destroys performance.

The Solution: Batch Your Operations

Batch all reads together, then all writes together. This lets the browser handle layout calculations efficiently in one pass instead of many.

Bad pattern (thrashing):

// DON'T do this in a loop or animation frame
element1.style.height = element2.offsetHeight + 'px'; // read then write
element3.style.width = element4.offsetWidth + 'px';   // read then write

Good pattern (batched):

// DO this instead
const height2 = element2.offsetHeight; // read
const width4 = element4.offsetWidth;   // read

element1.style.height = height2 + 'px'; // write
element3.style.width = width4 + 'px';   // write

The Analogy

Think of a librarian who must check inventory (read) and shelve books (write). If you ask them to check-shelve-check-shelve for 100 books individually, they waste time walking back and forth. If they check all 100 books first, then shelve them all, it's far more efficient.

Key Takeaway: Batch all DOM reads before any writes during animations to prevent layout thrashing and maintain smooth 60fps performance.