Last Updated: February 25, 2016
·
2.316K
· bluetidepro

Better jQuery Performance

When it comes to jQuery, performance is key. Be sure you are always caching your objects, chaining methods when you can, and using the correct api methods (In this example, using hide instead of css).

Bad:

$('span').click(function () {
    $('span').css("display", "none");
});
$('span').attr('style', 'background-color:yellow');
$('span').append('<a class="class">Test</a>');
$('span').append('<strong>Test2</strong>');
$('span').append('<a class="class">Test</a>');
$('span').append('<a class="class">Test</a>');

Better:

var span = $('span').css("background-color", "yellow");
var a = $('<a />').text('Test').addClass('class');
span.click(function () {
    span.hide();
});
span.append(a).append('<strong>Test2</strong>').append(a.clone(true)).append(a.clone(true));

1 Response
Add your response

Using multiple appends is a bad idea as it will cause a repaint (and potentially a reflow) of the DOM. A Nifty trick of the append method is that you can pass in multiple elements into one append call. I think your example would be better as:

span.append(a, '<strong>Test2</strong>', a.clone(true), a.clone(true));

though I get you were trying to show chaining as well.

over 1 year ago ·