Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does the DOM repaint during Javascript routines?

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?

like image 311
Mr. Lavalamp Avatar asked Feb 11 '23 11:02

Mr. Lavalamp


1 Answers

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

like image 97
jfriend00 Avatar answered Feb 14 '23 00:02

jfriend00