SyntaxStudy
Sign Up
jQuery Advanced 5 min read

Read-Write DOM Batching

Layout Thrashing

Interleaving DOM reads and writes causes forced reflows. Batch all reads first, then all writes to avoid thrashing.

Example
// 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";
});
Pro Tip

Reading layout properties (offsetHeight, getBoundingClientRect) after a write forces a synchronous layout calculation.