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:

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:

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: