Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which DOM element properties can cause the browser to perform a reflow operation when modified?

Tags:

javascript

dom

Which of these DOM element properties can cause browser to perform a reflow operation?

  • innerHTML
  • offsetParent
  • style
  • scrollTop
like image 348
Om3ga Avatar asked Jul 23 '12 16:07

Om3ga


1 Answers

In a nutshell, any property that causes an element to change size or move will cause a reflow because that change of size or position can affect other elements. Browsers spend effort trying to be as efficient as possible to identify what might need to be reflowed, but each has a different way of doing that.

Properties that cannot affect the size or position of an element such as a background color should not trigger a reflow, though there is no guarantee that every browser is smart enough to implement this.

In your list:

innerHTML changes the HTML of an object which certainly can affect size and position and will trigger at least a partial reflow.

offsetParent appears to me to be a read-only property that isn't something you set directly so reading it shouldn't cause a reflow if one wasn't otherwise already scheduled.

style is the gateway to lots of properties, including height and width which obviously would lead to at least a partial reflow.

scrollTop need not cause a reflow because layout is generally not changed, just a scroll position of one element (and it's children). The layout should remain the same, just a repaint is required.

It's probably worth saying also that most properties that lead to a reflow, don't immediately cause that reflow, but rather they schedule the reflow for some short time in the future. That way, if some javascript runs that changes a bunch of different properties, each of which needs a reflow, the browser isn't doing N reflows, but rather, it schedules the reflow, waits for the current javascript thread of execution to finish and then it carries out whatever reflows are needed just once. There are some properties that when read, cause all reflows that are pending to be done now because those properties could have inaccurate values if the reflows aren't done right away. You can read about that in this earlier post: Forcing a DOM refresh in Internet explorer after javascript dom manipulation

like image 77
jfriend00 Avatar answered Sep 26 '22 13:09

jfriend00