Last Updated: February 25, 2016
· 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).


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


var span = $('span').css("background-color", "yellow");
var a = $('<a />').text('Test').addClass('class'); () {

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 ·