a “Reflow” is when the browser recalculates the Layout of a page. (i.eis when the browser recalculates the positions or sizes of elements) Layout Thrashing is a rapid reflow process.
Minimal Example
for (let el of elements) {
let height = el.offsetHeight; // forces layout
el.style.height = (height + 10) + "px"; // DOM write
}Every iteration of this loop forces a reflow, leading to layout thrashing. A better way to achieve the same thing is:
let heights = elements.map(el => el.offsetHeight); // all reads
elements.forEach((el, i) => {
el.style.height = (heights[i] + 10) + "px"; // all writes
});In the second example, the browser will optimize and do only one layout pass.
Details & Specifics:
In the first example, for each iteration:
- read el.offsetHeight. If the layout is dirty, Flush(possibly reflow) then read.
- write el.height, then mark its subtree as dirty (rerender it asap) this means that for each iteration, there will be a reflow.
In the second example:
- read all the offsetHeight for all elements. Possibly flush only the first time.
- write all.
- each write Does mark the subtree as dirty, but browsers are smart enough to defer everything until the next paint or frame.