How browsers and users can optimize HTML rendering

Browsers are doing their best to restrict repaint/reflow to the area that covers the changed elements only. For example, a size change in an absolute/fixed positioned element only affects the element itself and its descendants, whereas a similar change in a statically positioned element triggers reflow for all the subsequent elements.

Another optimization technique is that while running pieces of JavaScript code, browsers cache the changes, and apply them in a single pass after the code was run. For example, this piece of code will only trigger one reflow and repaint:

var $body = $(‘body’);
$body.css(‘padding’, ‘1px’); // reflow, repaint
$body.css(‘color’, ‘red’); // repaint
$body.css(‘margin’, ‘2px’); // reflow, repaint
// only 1 reflow and repaint will actually happen

However, as mentioned above, accessing an element property triggers a forced reflow. This will happen if we add an extra line that reads an element property to the previous block:

var $body = $(‘body’);
$body.css(‘padding’, ‘1px’);
$body.css(‘padding’); // reading a property, a forced reflow
$body.css(‘color’, ‘red’);
$body.css(‘margin’, ‘2px’);
As a result, we get 2 reflows instead of one. Because of this, you should group reading element properties together to optimize performance

Don’t ask for computed styles excessively. If you need to work with a computed value, take it once, cache to a local var and work with the local copy. Revisiting the no-no example from above:
// no-no!
for(big; loop; here) {
el.style.left = el.offsetLeft + 10 + “px”;
el.style.top = el.offsetTop + 10 + “px”;
}

// better
var left = el.offsetLeft,
top = el.offsetTop
esty = el.style;
for(big; loop; here) {
left += 10;
top += 10;
esty.left = left + “px”;
esty.top = top + “px”;
}

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *