jQuery best performance practices

1. Passing the jQuery function a context can improve query performance

(function($) {
alert($(‘a’, document.getElementById(‘context’)).context.id); // Alerts “context”
alert($(‘a’, ‘#context’).context.nodeName); // No speed gain. Alerts “document”
})(jQuery);

2. Cache sets of selected elements that are used more than once
// Slow example:
for (i = 0; i < $('ul li').length; i++) { // Runs $('ul li') every iteration
$('ul').eq(i).text(); // Runs $('ul') every iteration
}
// Fast example:
var list = $('ul'); // Store query
var listLength = list.find('li').length; // Store length
for (i = 0; i < listLength; i++) { // Query pulled from memory
list.eq(i).text() // Query pulled from memory
}

3. Keep DOM changes to a minimum
// Slow example:
var list = $(‘ul’);
for (i = 0; i < 100; i++) {
list.append('

  • List item ‘ + i + ‘
  • ‘); // Interacts with the DOM 100 times
    }
    // Fast example:
    var listItems = ”; // Empty string
    for (i = 0; i < 100; i++) {
    listItems += '

  • List item ‘ + i + ‘
  • ‘; // Single string containing DOM structure
    }
    $(‘ul’).html(myListItems); // Use innerHTML to update the DOM only once

    4. Optimize by passing jQuery methods a key/value object
    // Slow example:
    $(‘a’).css(‘display’, ‘block’);
    $(‘a’).css(‘color’, ‘red’);
    $(‘a’).attr(‘title’, ‘Title Txt’);
    $(‘a’).atrr(‘href’, ‘http://www.jquery.com&#8217;);
    // Fase example:
    $(‘a’)
    .css({‘display’: ‘block’, ‘color’: ‘red’})
    .attr({‘title’: ‘Title Txt’, ‘href’: ‘http://www.jquery.com&#8217;});

    5. Optimize by passing multiple selectors to the jQuery function
    // Slow example:
    $(‘#div1’).hide();
    $(‘#div2’).hide();
    $(‘#div3’).hide();
    // Fast example:
    $(‘#div1, #div2, #div3’).hide();

    6. Optimize by leveraging chaining
    // Slow example, creates three instances of jQuery object
    $(‘div .open’).hide();
    $(‘div .close’).show();
    $(‘div’).fadeIn();
    // Fast example, uses chaining to re-purpose the orginal wrapper set
    $(‘div’)
    .find(‘.open’)
    .hide()
    .end()
    .find(‘.close’)
    .show()
    .end()
    .fadeIn();
    // Alternatively, do this:
    var $div = $(div); // Cache the wrapper set
    $div.find(‘.open’).hide();
    $div.find(‘.close’).show();
    $div.fadeIn();
    Use

    7. Use the native for loop when dealing with big loops
    Native browser functions are always faster! The question that needs to be answered in most cases is:
    How much faster? In most cases the increase is negligible. If that is the case, go ahead and use the
    jQuery each() method or utility function over a native JavaScript for loop.
    The rule of thumb I follow is most small looping tasks (less than a 1000 iterations) are perfectly
    suited for the jQuery each() utility method. The abstracted jQuery solutions for looping allow for
    easier coding, which I value over the negligible speed increase won by using a native approach with
    smaller loops. Truth be told, if I cannot feel a significant difference when using a page, I do not worry
    about optimization.
    Once you get into bigger loops (1000+ iterations) you might start measuring the difference by
    documenting the time it takes for a native function to execute vs. a jQuery solution. This test
    becomes critical when it comes to Internet Explorer, which runs notoriously slow with big loops of any
    kind.

    8. Apply visual changes via ID and Class vs. manipulating style properties

    .newStyles {
    background-color: red;
    display:block;
    height:100px;
    width:100px;
    }

    (function($) {
    // Slow example:
    $(‘div’).css({
    ‘display’: ‘block’,
    ‘width’: ‘100px’,
    ‘height’: ‘100px’,
    ‘background-color’: ‘#f00’
    });
    // Fast example:
    $(‘div’).addClass(‘newStyles’);
    })(jQuery);

    Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s