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.
Code
// 读写交错就是 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.
documentexist 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
CSS Flexbox PlaygroundInteractively test CSS flexbox container and item properties with a live preview. Adjust justify-content, align-items, flex-direction, and flex-grow to see layout changes.CSS Grid PlaygroundExperiment with CSS grid layout properties interactively. Define columns, rows, gaps, and areas while watching the grid template update in a live visual preview.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.