Layout thrashing and profiling
Definition and purpose
Layout thrashing is repeated alternation of layout-invalidating writes and geometry reads that can force synchronous layout.
Read once, write twice
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } #a { width: 120px; } </style> </head> <body> <div id="a">Source</div> <div id="b">Target</div> <div id="c">Target</div> <script> const source=document.querySelector("#a"); const targets=[document.querySelector("#b"),document.querySelector("#c")]; const width=source.getBoundingClientRect().width; targets.forEach(el=>el.style.width=width+"px"); </script> </body></html>Both targets use the same read from the source.
Syntax and mental model
For example, changing width then reading offsetWidth in every loop iteration can force layout work repeatedly. If all targets depend on one source width, read once before writing all target widths. If the source depends on the targets, the algorithm must be redesigned rather than blindly moving reads. Record both variants in the Performance panel with identical DOM and input; examine layout events and forced-reflow insights. The fixture checks final geometry, not timing.
Box sizing agreement
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } #a { width: 140px; } #b, #c { box-sizing: border-box; padding: 8px; } </style> </head> <body> <div id="a">Source</div> <div id="b">Target</div> <div id="c">Target</div> <script> const source=document.querySelector("#a"); const targets=[document.querySelector("#b"),document.querySelector("#c")]; const width=source.getBoundingClientRect().width; targets.forEach(el=>el.style.width=width+"px"); </script> </body></html>Border-box keeps padding inside the measured target width.
Common mistakes
Do not assume requestAnimationFrame alone prevents forced layout. Reads after invalidating writes can still trigger work.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Containment and content visibility. Next lesson: Layout stability and font performance.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Layout thrashing and profiling — knowledge check
Five questions on layout thrashing and profiling.
Which sequence may force repeated layouts?
When is reading once valid?
Does requestAnimationFrame guarantee no forced layout?
Which tool checks actual layout work?
What do equal final widths prove?