Batch Reads And Writes To Avoid Layout Thrashing

Reading layout after every style write forces synchronous reflow; collect all offsetHeight reads first, then apply writes so the browser lays out once.

JavascriptResilience

Code

javascriptsnippet
20 lines
// 读写交错就是 layout thrashing:每次 offsetHeight 都强制同步布局
// 正确姿势是 batch:先把要读的布局值一次读完,再一口气写

const cards = [];
for (let i = 0; i < 3; i++) {
  const card = document.createElement("div");
  card.style.height = `${20 + i * 15}px`;
  document.body.append(card);
  cards.push(card);
}

// 读批:先收集所有布局值
const heights = cards.map((card) => card.offsetHeight);
console.log("read :", heights.join(","));

// 写批:再统一修改,布局只重算一次
cards.forEach((card) => {
  card.style.height = `${Math.max(...heights)}px`;
});
console.log("after:", cards.map((card) => card.offsetHeight).join(","));

Inside the snippet

The cycling part of this snippet is for (let i = 0; i < 3; i++).

The file’s state is a handful of top-level bindings: cards, heights.

Caveats

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.
  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Using it

The run emits 2 labeled sections — read :, after: — one per step.

Key statements

const heights = cards.map((card) => card.offsetHeight);
cards.forEach((card) => {
  card.style.height = `${Math.max(...heights)}px`;
});

Interactive Tools for This Topic

FAQ

Does Batch Reads And Writes To Avoid Layout Thrashing run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.