Course contentsShow
← Web Development
Lesson 2594 of 2,98246. Animation LibrariesFree lesson

Avoiding Layout Thrashing

How reading and writing layout properties in sequence causes forced reflows.

Avoiding Layout Thrashing

What you'll learn: How reading and writing layout properties in sequence causes forced reflows and destroys animation performance.

The Problem

Layout thrashing (also called "forced synchronous layout") occurs when you repeatedly read layout properties (like offsetHeight, getBoundingClientRect()) and immediately write properties that affect layout (like style.height or classList.add()), forcing the browser to recalculate styles and layout over and over within the same JavaScript execution frame.

Think of it like measuring and cutting wood: if you measure one board, cut it, measure the next, cut it, measure again... you're constantly switching between tools. Instead, you should measure all boards first, then do all the cuts.

Why It Destroys Performance

When you read a layout property, the browser must ensure all pending style changes are applied and layout is recalculated to give you an accurate value. If you then write a style change and immediately read again, you force another complete recalculation—potentially dozens of times per frame instead of once.

The Solution Pattern

Batch all your reads together, then batch all your writes together:

// ❌ BAD: Read-write-read-write (thrashing)
elements.forEach(el => {
  const height = el.offsetHeight;  // Read (forces layout)
  el.style.height = height + 10 + 'px';  // Write
});

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

This simple restructuring prevents forced reflows and keeps your animations at 60fps.

Key Takeaway: Always separate your layout reads from your layout writes—batch reads first, then batch writes—to avoid forcing the browser to recalculate layout multiple times per frame.