Eugene
Eugene

Reputation: 963

jQuery $(...).empty().append(...) slows down whole page after several executions

I'm using $('#...').empty().append(html)-like construction to update content on AJAX success. After 5-6 requests whole page goes slower and slower with each request (:hover takes more time to appear, JS slows down, etc.). This happens in any browser. The more content is loaded, the faster slowdown happens.

I think I'm missing some cleanup somewhere. Any advice?

Code:

query = function (uri, data) {
    $.ajax({
        url: uri,
        cache: false,   
        data: data,
        success: processResponse,
        method: data?'POST':'GET',
    });
    return false;
}

processResponse = function (data) {
    $('#rightplaceholder').empty();
    $('#rightplaceholder').append(data);
}

$('#button').click( function () { query('/foo'); } );

I've also tried disabling all JS not directly related to loading this fragment - with no luck.

Upvotes: 2

Views: 2483

Answers (3)

sg3s
sg3s

Reputation: 9567

In general jQuery functions have a little lot of overhead, and I'm guessing that the combination of your settings and usage create a memory leak / slowness somewhere in the system. So +1 for finding this.

If you're really just replacing html, you could use the native innerHTML property, it is well supported and does what you're trying to do here. It is usually the best method for replacing larger amounts of html. And as mentioned, it's even better to prevent replacing html a lot.

Example:

$('#rightplaceholder').innerHTML = data;

Make sure to set .innerHTML after appending the DOM element to the page, should prevent memory leaks. So using it on an existing element should be fine.

Upvotes: 2

user113716
user113716

Reputation: 322452

Sounds like a memory leak caused by whatever supplementary JavaScript you (or the data you're loading) is running.

Remove all unnecessary code, or when removing elements from the page that are added by other code, make sure you use their API to do so, so it can have a chance to clean up.

Upvotes: 1

Blazemonger
Blazemonger

Reputation: 92893

Try using $('#rightplaceholder').html(data); instead, combining two DOM manipulations into one.

Also: change cache: false to true to speed up multiple AJAX requests. If you're not submitting data, then there should be no reason not to cache the results.

Upvotes: 4

Related Questions