What is layout thrashing and how do you avoid it?
Answer
Layout thrashing (also called forced synchronous layout) occurs when JavaScript reads a layout-dependent property (e.g., element.offsetWidth) immediately after writing a style change, forcing the browser to recalculate layout synchronously before the main thread can proceed. This makes a single style change expensive and can cause severe performance issues when done in a loop. Example of thrashing: for (const el of elements) { el.style.width = box.offsetWidth + "px"; } — reads offsetWidth (forces layout recalculation) then writes, repeated N times. Fix: Batch reads, then writes: const width = box.offsetWidth; for (const el of elements) { el.style.width = width + "px"; }. Properties that force layout: offsetWidth/Height, scrollTop/Left, clientWidth/Height, getBoundingClientRect(), getComputedStyle(). Use requestAnimationFrame: group DOM writes in rAF callback — browsers batch paints before the next frame. CSS transform/opacity: use these for animations instead of properties that trigger layout. will-change: hint for elements that will animate — promotes to own compositor layer. FastDOM library schedules reads and writes correctly.
Previous
What is the browser performance API and how do you measure performance?
Next
What is resource prioritization in browsers?
More Web Performance Questions
View all →- Intermediate How do you optimize React applications for performance?
- Intermediate What is the browser performance API and how do you measure performance?
- Intermediate What is resource prioritization in browsers?
- Intermediate How does SSR (Server-Side Rendering) improve performance?
- Intermediate What is a performance budget?