JavaScript Interview Question #158
What is layout thrashing?
Performance, Browser APIs, Rendering & Modern Web Architecture Senior Advanced
Quick Interview Answer
Layout thrashing occurs when JavaScript repeatedly alternates DOM writes that invalidate layout with reads that require up-to-date layout information. The browser may be forced to perform synchronous layout calculations many times.
Detailed Explanation
Layout thrashing occurs when JavaScript repeatedly alternates DOM writes that invalidate layout with reads that require up-to-date layout information. The browser may be forced to perform synchronous layout calculations many times.
A common optimization is to group required layout reads together and then batch writes, reducing unnecessary forced recalculations.
Code Example
// Better: read first, then write.
const items = [...document.querySelectorAll(".item")];
const widths = items.map(
item => item.getBoundingClientRect().width
);
items.forEach((item, index) => {
item.style.width = `${widths[index] + 10}px`;
});