javascriptperformancedomreflow

When does reflow happen in a DOM environment?


What kinds of activities will trigger reflow of web page with DOM?

It seems there are different points of view. According to http://www.nczonline.net/blog/2009/02/03/speed-up-your-javascript-part-4/, it happens

However, according to http://dev.opera.com/articles/view/efficient-javascript/?page=3, taking measurement triggers reflow only when there is already reflow action queued.

Does anybody have any more ideas?


Solution

  • Both articles are correct. One can safely assume that whenever you're doing something that could reasonably require the dimensions of elements in the DOM be calculated that you will trigger reflow.

    In addition, as far as I can tell, both articles say the same thing.

    The first article says reflow happens when:

    When you retrieve a measurement that must be calculated, such as accessing offsetWidth, clientHeight, or any computed CSS value (via getComputedStyle() in DOM-compliant browsers or currentStyle in IE), while DOM changes are queued up to be made.

    The second article states:

    As stated earlier, the browser may cache several changes for you, and reflow only once when those changes have all been made. However, note that taking measurements of the element will force it to reflow, so that the measurements will be correct. The changes may or may not not be visibly repainted, but the reflow itself still has to happen behind the scenes.

    This effect is created when measurements are taken using properties like offsetWidth, or using methods like getComputedStyle. Even if the numbers are not used, simply using either of these while the browser is still caching changes, will be enough to trigger the hidden reflow. If these measurements are taken repeatedly, you should consider taking them just once, and storing the result, which can then be used later.

    I take this to mean the same thing they said earlier. Opera will try its hardest to cache values and avoid reflow for you, but you shouldn't rely on its ability to do so.

    For all intents and purposes just believe what they both say when they say that all three types of interactions can cause reflow.

    Cheers.