4

I apologize if this question already exists, but I couldn't find it.

In the following code, at which points will a page reflow/repaint be triggered, assuming a DOM object is updated at each point?

(function() {

  //POINT A

  for (var a=0; a<2; a++) {

    //POINT B

    for (var b=0; b<2; b++) {
      //POINT C
    }
    //POINT D

    for (var b=0; b<2; b++) {
      //POINT E
    }
    //POINT F

  }

  //POINT G

})();

//POINT H

Essentially, I'm not sure if the DOM has the ability to update in the middle of functions, loops, etc. Can it update every time an element is moved? Only after exiting loops? After all active loops have exited? After all functions have finished?

Mr. Lavalamp
  • 1,860
  • 4
  • 17
  • 29

1 Answers1

9

By default, the browser will wait until the current thread of execution finishes and do one consolidated reflow and repaint (as this is considered more efficient than doing many reflows and repaints). This is not specified in any specification so the browser can implement as it wants to.

But, there are some specific operations that will generally trigger a reflow (and sometimes a corresponding repaint). These operations are operations (requesting certain properties related to the position of elements) which can only be completed when an accurate reflow has been done. So, it is possible to manually trigger a reflow by requesting one of these properties.

For example, requesting the .offsetHeight property of a non-absolutely positioned element will force a pending reflow at that point.

Other properties that trigger a pending reflow here: Which DOM element properties can cause the browser to perform a reflow operation when modified?

Another list of properties here: http://gent.ilcore.com/2011/03/how-not-to-trigger-layout-in-webkit.html

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Is there a list of these properties somewhere? Also, if I understand you correctly, it sounds like IN GENERAL if each of these points just changed the 'position' property of absolutely positioned elements, a reflow would trigger after Point H? – Mr. Lavalamp Nov 28 '14 at 22:48
  • @Mr.Lavalamp - in general, geometry properties that depend upon proper layout to be accurate will trigger a pending layout if that layout is required in order to accurately report the property. For example `.offsetHeight` is one such property. But, absolutely positioned objects have a known position without recomputing layout (since their position is not dependent upon layout). – jfriend00 Nov 28 '14 at 23:00
  • @Mr.Lavalamp - see [this answer](http://stackoverflow.com/questions/11616619/which-dom-element-properties-can-cause-the-browser-to-perform-a-reflow-operation) for a list of properties that trigger a reflow. – jfriend00 Nov 28 '14 at 23:28