Layout Thrashing
Interleaving DOM reads and writes causes forced reflows. Batch all reads first, then all writes to avoid thrashing.
Interleaving DOM reads and writes causes forced reflows. Batch all reads first, then all writes to avoid thrashing.
// BAD: read-write-read-write = forced reflows
items.forEach(el => {
const h = el.offsetHeight; // read → forces layout
el.style.height = h + 10 + "px"; // write
const w = el.offsetWidth; // read → forced reflow!
el.style.width = w + 10 + "px"; // write
});
// GOOD: read all, then write all
const measurements = items.map(el => ({ h: el.offsetHeight, w: el.offsetWidth }));
items.forEach((el, i) => {
el.style.height = measurements[i].h + 10 + "px";
el.style.width = measurements[i].w + 10 + "px";
});
Reading layout properties (offsetHeight, getBoundingClientRect) after a write forces a synchronous layout calculation.