5 jQuery Performance Tips

February 13th, 2010 | posted in blog, jQuery | 1 Comment »

In the world of Web 2.0 applications, speed is one of the most important things to take in mind. Every such web application often uses a large amount of JavaScript code which is run in the users’ browser. Of course using a JavaScript library is essential to speed up the development of these applications, but using it the wrong way exponentially decreases the execution speed of the code, so the application becomes very slow and unusable.

I’ve put together 5 performance tips for the most used JavaScript library, jQuery.

1. Always get elements by #id

This is the fastest selector in jQuery for finding the required element.

Always use it before tag selectors and class selectors. Ordered by speed:

  1. $(“#some-id”)
  2. $(“div”)
  3. $(“#some-id div”)
  4. $(“#some-id div.some-class”)
  5. $(“div.some-class”)
  6. $(“.some-class”)

2. Minimize selection operations

When using a loop, avoid selecting an element or elements in every iteration.

for (var i=0; i<$("#table tr").length; i++){
 ...some code here...
}

Cache the selection like this:

var len = $("#table tr").length;
for (var i=0; i<len; i++){
 ...some code here...
}

3. Insert one instead of many DOM elements

Wrap all your code into one element and insert it in the DOM tree with the .html() method.

Instead of:

var html = '
 <p>One</p>
 <p>Two</p>
 <div>Three</div>
';
$('#someid').html(html);

Wrap the code in a div or other element, and then use the .html() method.

var html = '
<div>
 <p>One</p>
 <p>Two</p>
 <div>Three</div>
</div>
';
$('#someid').html(html);

4. Give your selectors a context

As I said before, the fastest way to select elements is by #id, so, if you must use classes to select elements, give them a context.

Instead of:

$('.someclass').css('background-color' '#FFFFFF');

Use this:

$('.someclass',#someclass-container).css('background-color' '#FFFFFF');

5. Use jQuery chaining capabilities

One of the coolest things in jQuery is the possibility to chain your method calls. Example:

$('#someid').addClass('error').css('color','red').fadeOut('slow');

One Comment

[...] За примери на код за секоја од точките, плус објаснување посетете го http://goranmitev.com/2010/02/13/5-jquery-performance-tips/ [...]

Commented on: 18.03.2010 at 11:09

Leave a Comment