[whatwg] Reliably Minimize Reflows

Joseph Pecoraro joepeck02 at gmail.com
Sat Sep 26 09:04:38 PDT 2009


A task that developers are often faced with is applying many style  
updates to multiple Nodes in the DOM.  An example would be showing/ 
hiding all divs with the "foo" style class:

   // Hide multiple divs
   var foos = document.getElementsByClassName('foo');
   for (var i=0, len=foos.length; i < len; ++i)
     foos[i].style.display = 'none';

As I understand it, if there are 20 .foo elements then updating the  
style on each _could_ cause 20 individual reflows.  It would be best  
if the developer can narrow that down to a single reflow.  Minimizing  
reflows is a well known suggestion for speeding up web pages [1][2].  
The most natural and generalized API that I can think of would be  
something like:

   // Single reflow would be triggered at the end of batchUpdate
   document.batchUpdate(function() {
     ...
   });

Opera mentions a little about its reflow algorithms at [2] with raises  
some interesting points.  Here is the relevant portion:

"Browsers may choose to wait until the end of a script thread before  
reflowing to show the changes. Opera will wait until enough changes  
have been made, enough time has elapsed, or the end of the thread is  
reached. This means that if the changes happen quickly enough in the  
same thread, they may only produce one reflow. However, this cannot be  
relied on, especially considering the various different speeds of  
devices that Opera runs on."

The idea here is that "batchUpdate" would be a reliable way to  
minimize reflows.  Does this sound like a worthwhile improvement?

Cheers,
Joseph Pecoraro

[1]: http://code.google.com/speed/articles/reflow.html
[2]: http://dev.opera.com/articles/view/efficient-javascript/?page=3



More information about the whatwg mailing list