Wednesday, June 2, 2010

10 Tips to improve your jquery code performance.

I’ve been coding using jQuery since shortly after it came out, and well — I’ve been using it almost every work day. Here is a few tips that have saved me time.\

#1: Use data method instead of storing data inside theDOM.

The mistake I see people making all the time is this:

$('selector').attr('alt', 'this is the data that I am storing'); 
// then later getting that data with 
$('selector').attr('alt');


Why is this a bad thing? Because “alt” has absolutely no meaning whatsoever, as well as HTML is not meant to store data.



Instead use the data method in jQuery. It allows you to associated data with an element on the page.



$('selector').data('meaningfullname', 'this is the data I am storing');
// then later getting the data with
$('selector').data('meaningfullname');


This allows you to store data with meaningful names and as much data as you want on any element on the page. It is a really amazing utility and something I’ve come to rely on.



#2: Take advantage of jQuery’s built-in custom selectors.



jQuery has a plentiful amount of selectors that are beyond basic CSSselectors, so use them. Some that I use are:




  • :input example: get all the inputs on the page regardless if they are checkbox, textarea or select list – use :input


  • [attribute=value] example: find an input with the name,“container”- use input[name='container']


  • :eq(index) example: get the fourth table on the page – usetable:eq(3)



#3: If you are Manipulating the DOM a lot, use livequery.



When you add elements to the page a lot, attaching events to them and running functions on them then use Brandon Aaron’s livequery plugin. This way you can do things like:



$('div.edit').live('click', function(){ ... });


Then whenever you add a div to the page with class “edit” it will attach that click event. This works for all other events, as well as if you want to run a function on an element right when it is added you can do this:



$('span.flag').livequery(function(){
  // run this function when a span with class "flag" 
is added to the page
});


#4: Use jQuery form plugin to submit files via Ajax.



If you use Mike Alsup’s jQuery form plugin you can use it to submit files via Ajax. It uses a trick with an iframe to submit the data. Just put in an input type file, then use $(form).ajaxSubmit(); and you are good to go.



#5: Use classes as flags.



If you aren’t storing data, but need to set a flag on an element use a class. What do I mean by a flag? Well, for instance if you are in"edit mode"of a form you might use the class,“editing”.With jQuery you can add a class with the addClass method and then check later if an element has the class with the hasClass method.



#6: Use JavaScript native for() loop instead of jQuery's $.each()helper function.



Native browser functions are always faster then any other helper functions that were built to add an abstraction layer. In case you are looping through an object that you have received as JSON, I highly recommend you rewrite your JSON to contain an array rather than an object.



#7 : Do NOT append an element to the DOM in your loop.



This one is probably one of the most important tips that will significantly improve your code performance. It is so important that I will repeat myself. Do not append a new element to the DOM in your loop statement. Instead store it in a variable as text and append it to the DOM after your loop finishes like this:



// DO NOT DO THIS 
for (var i=0; i<=rows.length; i++)  
{ 
    $('#myTable').append('<tr><td>'+rows[i]+'</td></tr>'); 
} 
// INSTEAD DO THIS 
var tmp = ''; 
for (var i=0; i<=rows.length; i++)  
{ 
    tmp += '<tr><td>'+rows[i]+'</td></tr>'; 
} 
$('#myTable').append(tmp);


#8 : If you have a lot of elements to be inserted into the DOM, surround them with a parent element for better performance.



When you have a lot of elements to insert into the DOM tree it takes time to add them all. Somehow adding one element with 1000 children is faster than adding 1000 children separately. You can search this site for performance tests that prove it.

So, to improve our previous example's performance let's cover <tr>'s with <tbody> tag like this:



var tmp = '<tbody>';
for (var i=0; i<=rows.length; i++)
{
    tmp += '<tr><td>'+rows[i]+'</td></tr>';
}
tmp += '</tbody>';
$('#myTable').append(tmp);


#9 : Don't use string concatenation, instead use array's join()method for a very long strings.



var tmp = [];
tmp[0] = '<tbody>';
for (var i=1; i<=rows.length; i++)
{
    tmp[i] = '<tr><td>'+rows[i-1]+'</td></tr>';
}
tmp[tmp.length] = '</tbody>';
$('#myTable').append(tmp.join(''));


#10 : And the last but not least use setTimeout() function for your long list looping and concatenation functions.



This will make sure that page does not freeze while it loops through the long list of data and lets users to work with your page meanwhile.

It was well mentioned in comments that setTimeout() function should be used to split your code processing into little chunks so your browser does not freeze up like this:



function myFunk(data){ 
    // do processing 
    if(!has_finished) 
        setTimeout("myFunk()", 100); 
}

People who read this post also read :



If you liked my post then,

Subscribe to this site via Email:

Click here to Subscribe to FREE email updates from "itrickz", so that you do not miss out anything that can be valuable to you and your blog!!

DropJack!
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

5 comments: on "10 Tips to improve your jquery code performance."

Learnphp said...

To learn PHP,mysql,ajax,html,javascript,jquery with advanced concepts, you can visit Advanced PHP tutorial

Corey Ballou said...

#7 and #8 both use string concatenation in the example, whereas you use the correct (and fast) implementation of array based storage in #9. You should consider fixing #7 and #8 to use arrays, perhaps moving the numbering around and placing them after #9. Your iteration is also a little convoluted. I fixed things up for you a bit.

var tmp = [];
var len = rows.length;
tmp.push('<tbody>');
for (var i = 0; i < len; i++) {
    tmp.push('<tr><td>'+rows[i]+'</td></tr>');
}
tmp.push('</tbody>');
$('#myTable').append(tmp.join(''));

shyam raj said...

Thanx for your suggestions corey ballou.I will look forward it..

Anonymous said...

setTimeout should take a function instead of a string. When you pass a string an eval occurs, and this should be avoided in general. So in your example you would have either:
setTimeout(myFunk, 100);
-or-
setTimeout(function() { myFunk(); }, 100);

Andreas Grabner said...

the biggest performance problems with jquery that I've seen are CSS Selectors by Class Name -> huge performance problem on IE - here is a blog with details: http://blog.dynatrace.com/2009/11/09/101-on-jquery-selector-performance/

Post a Comment