Performance and DevTools
Avoid layout thrashing
Batch DOM reads and writes so JavaScript does not repeatedly force synchronous layout inside a loop.
8 minute lesson
A DOM or style write can invalidate layout. If JavaScript immediately asks for current geometry, the browser may have to calculate layout synchronously before returning the value.
This loop alternates writes and reads:
for (const item of items) {
item.style.width = `${containerWidth}px`
console.log(item.offsetHeight)
}
Each offsetHeight may force pending layout work, and the next iteration invalidates it again. Repeating that pattern is layout thrashing.
Batch the phases instead:
const heights = items.map(item => item.offsetHeight)
items.forEach((item, index) => {
item.style.width = `${containerWidth}px`
item.dataset.previousHeight = heights[index]
})
Real code may need a different calculation, but the rule stays useful: group required reads, compute values, then group writes. Cache dimensions when they are valid rather than asking the browser repeatedly.
Do not remove every geometry read on principle. Measure a representative interaction in the Performance panel and look for repeated layout events or forced-layout warnings tied to the same function. Fixing one measured loop is more valuable than wrapping arbitrary DOM code in scheduling helpers.
Create 500 elements and run both patterns while recording. Compare time spent in layout and the number of layout events. Repeat the recording because tiny examples can be dominated by profiling noise.
Lesson completed