Senior LevelHTML & Semantic Web
How do you diagnose and eliminate Layout Thrashing (Forced Synchronous Reflow)?
❓ Interview Prompt: Explain Forced Synchronous Reflow, Layout Thrashing, reading geometric DOM properties (offsetHeight, getBoundingClientRect) after writes, and FastDOM.
Layout Thrashing (Forced Synchronous Reflow) occurs when JavaScript reads geometric DOM properties (e.g. 'element.offsetHeight', 'element.getBoundingClientRect()') immediately after writing DOM styles.
The Performance Issue:
The browser is forced to flush pending style recalculations and execute a synchronous layout recalculation in the middle of JavaScript execution!
Fix:
Batch all DOM read operations together first, then batch all DOM write operations (or use libraries like FastDOM).
Code Implementation Example
javascript
// ❌ BAD: Layout Thrashing (Read-Write loop forces repeated synchronous reflows!)
elements.forEach(el => {
const h = el.offsetHeight; // READ
el.style.height = (h + 10) + 'px'; // WRITE
});
// ✅ GOOD: Batched Reads then Batched Writes
const heights = elements.map(el => el.offsetHeight); // BATCH READS
elements.forEach((el, i) => el.style.height = (heights[i] + 10) + 'px'); // BATCH WRITES💡Diagnosing and eliminating Forced Synchronous Reflow by batching DOM reads and writes.
🎯 Interview Key Takeaway
Batch all DOM geometry reads before performing DOM writes to prevent Forced Synchronous Reflow and Layout Thrashing.
#Layout Thrashing#Reflow#Performance#Senior
Back to all HTML & Semantic Web Questions→