Performance·29 questions

How to optimize work with styles and avoid forced layout reflows in the browser?

Answer

Forced layout recalculation, known in the professional community as layout thrashing, occurs in situations where JavaScript first changes element properties and then immediately requests their geometric parameters. The browser is forced to immediately recalculate the layout of all elements on the page to provide an up-to-date answer, which leads to colossal CPU time consumption and a drop in frame rate.

To avoid such problems, it is necessary to clearly separate the property reading phases and the style writing phases in the application code. Reading parameters such as element width, height, or position via special properties forces the browser to synchronously perform page layout. If this is done inside loops or frequent event handlers, interface performance drops to critical values.

Modern development standards offer effective approaches to prevent unnecessary layout recalculations. The main optimization recommendations include the following rules.

Group all DOM property reading operations at the very beginning of the function, before any changes have been made.
Perform all style and document structure changes only after all necessary data has been read.
Use special task schedulers to separate reading and writing if the application logic is scattered across different modules.
Minimize direct access to styles from scripts by replacing them with toggling pre-prepared CSS classes.

An additional optimization tool is hardware-accelerated animation using transform and opacity properties. Changes to these properties are processed by the GPU without affecting the geometry of other page elements, allowing for smooth playback without lags or stutters.

Was this answer helpful?

More questions in this topic

Related questions from other topics