Browsers compute style and layout lazily. A DOM or style write only marks part of the tree dirty, and the work normally runs once, in the next frame's rendering update. But geometry APIs are defined in terms of boxes: CSSOM View's offsetWidth returns the width of the border boxes of the element's fragments. To answer correctly after a write, the browser has to run style and layout right then, synchronously, in the middle of your script. That's a forced synchronous layout (also called forced reflow). No spec uses the term; it's the cost of lazy layout showing through.
Reads that need current layout:
offsetTop/Left/Width/Height/Parent,clientWidth/Height/Top/LeftscrollTop,scrollLeft,scrollWidth,scrollHeight; calls likescrollTo()andscrollIntoView()getBoundingClientRect(),getClientRects(),document.elementFromPoint()innerText, which returns text as renderedgetComputedStyle()values that resolve to used values, such aswidthandheight
Each of these forced a layout in Chrome 156 when read right after a width change.
getComputedStyle(el) itself returns a live object and computes nothing. Reading color from it needs style only; reading width needs layout. textContent and attributes need neither.
One forced layout is cheap when nothing is dirty. The problem is layout thrashing: writes and reads alternating in a loop, so every read pays for a full layout. Fixes:
- Batch: do every read, then every write.
- Read at the start of a
requestAnimationFramecallback, before writing. - Let
ResizeObserverdeliver sizes after the browser's own layout instead of reading them in a loop.