Avoiding Forced Synchronous Layouts (Layout Thrashing)
You'll learn how to prevent performance disasters caused by repeatedly forcing the browser to recalculate layouts within a single frame.
What Is Layout Thrashing?
Layout thrashing (also called forced synchronous layout) happens when you alternate between reading layout properties and writing DOM changes within the same JavaScript execution. Each time you read a layout property (like offsetHeight or scrollTop) after making a DOM change, you force the browser to stop everything and recalculate the entire layout immediately—even if it just calculated it milliseconds ago.
Think of it like a chef who chops one vegetable, then measures the pot, then chops another vegetable, then measures the pot again. Instead of batching all the chopping and then measuring once, they're forcing themselves to stop and start repeatedly. This creates massive inefficiency.
The Problem Pattern
// BAD: Interleaved reads and writes
elements.forEach(el => {
const height = el.offsetHeight; // READ (forces layout)
el.style.marginTop = height + 10 + 'px'; // WRITE
// Next iteration forces ANOTHER layout!
});
The Solution: Batch Reads, Then Writes
// GOOD: Separate reads from writes
const heights = elements.map(el => el.offsetHeight); // All READs first
heights.forEach((height, i) => {
elements[i].style.marginTop = height + 10 + 'px'; // Then all WRITEs
});
By separating your DOM reads from your DOM writes, the browser can optimize its rendering pipeline naturally. It calculates layout once after all writes are complete, rather than being forced to recalculate repeatedly.
Key Takeaway: Batch all DOM reads together, then batch all DOM writes together—never interleave them—to avoid forcing the browser into expensive synchronous layout recalculations that kill frame rates.