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.