Hi,

I just want to share what I found out today.

I was trying to update records of a table with the html-response of an
ajax request. First I tried $('#list').load() to just replace the
content of $('#list') with the ajax-response. The performance was
remarkable poor. I thought it's due to the ajax request and replaced
load() with a call to $.ajax() and assigned the response data with $
('#list').html(data), but the performance didn't get better. Thanks to
Firebug I realized that the performance was not an issue of the ajax
request but the replacing of the content of $('#list').

When poking around with different approaches to replace the records, I
found out, that the clearing of the content is the critical point.
More precisely the method empty().

Digging into jQuery Core I noticed that load() and html() both use
empty() - to be exact load() just calls html(). The empty() method
properly removes nodes from the DOM to prevent memory leaks but has a
significant impact on performance.

Replacing empty() with just setting the property innerHTML to '', e.g.

$('#list')[0].innerHTML = '';
$('#list').append(data);

instead of

$('#list').html(data);

the performance can be dramatically improved. In my case you don't
have to measure the difference, you can see it.

As I'm not a JavaScript guru I didn't dig any deeper, if the empty
method can be improved. Surely it does a good job to remove nodes
properly but in my case
the approach with html() is so slow that it's just not applicable.

To be on the save side I extended jQuery and defined a html()-method
of my own. So in the case of occuring problems in the future you just
have to fix the problem at one place.

$.fn.stkbaseHtml = function(value){
   return this.each(function() {
      if(value == undefined) {
         return (this.length ? this.innerHTML : null)
      } else {
         this.innerHTML = '';
         $(this).append(value);
      }
   });
};

Any comments to this approach especially concerning the memory leak
problem are welcomed!

michael

Reply via email to