Saturday, February 14, 2009

jQuery: performance of DOM manipulation

I tried moving some html that didn't have a direct relation to the meaning of my content, but more with layout aspect, to the client-side by writing a jQuery plugin for it. This in order to heighten the separation of concerns. The plugin performs some DOM manipulation in order to apply a drop shadow effect as seen in the following image (left side without plugin applied, right side with):



To accomplish this the crucial part of the plugin performs the following DOM manipulation:


[javascript]
elementToWrap.html(
'<div class="frame" style="width: 157px;">' +
elementToWrap.html() +
'<div class="right_shadow">' +
'<div class="shadow_top_right"></div>' +
'<div class="shadow_right" style="height: 93px;"></div>' +
'</div>' +
'<div class="bottom_shadow">'
'<div class="shadow_bottom_left"></div>' +
'<div class="shadow_bottom" style="width: 143px;"></div>' +
'<div class="shadow_bottom_right"></div>' +
'</div>' +
'</div>'
);
[/javascript]


However, when I started using it in my site, page loads seemed sluggish. Especially on the thumbnail pages, with some 20 images to apply the plugin to. I was in for some performance measurements. With the Firefox plugin Firebug this is easy. You surround the code for which you want to measure the execution time with the following code:


[javascript]
console.time('applyShadow');
...
console.timeEnd('applyShadow')
[/javascript]

After which the firebug console will present you with timing in milliseconds for each time the plugin wraps an image with the forementioned divs. It looks as follows on my 2,4GHz quadcore:




In total it adds up to some 100-200ms for the 20 images on my homepage and even more on other pages. I'm afraid that with current browsers - even on Google Chrome you could notice the difference - this kind of offloading html generation to the client-side isn't performant enough. If you want to run a bleeding fast website DOM manipulation should be kept to a minimum. Of course it is still very useful and acceptable when reacting on user interactions (like with the jQuery UI dialogs).


Some very useful tips when it comes to using jQuery and performance can be found over here:


http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx

No comments:

Post a Comment