1. Load the framework from Google Code
Google have been hosting several JavaScript libraries for a while now on Google Code and there are several advantages to loading it from them instead of from your server. It saves on bandwidth, it'll load very quickly from Google's CDN and most importantly it'll already be cached if the user has visited a site which delivers it from Google Code.This makes a lot of sense. How many sites out there are serving up identical copies of jQuery that aren't getting cached? It's easy to do too...
<script src="http://www.google.com/jsapi"></script> <script type="text/javascript"> // Load jQuery google.load("jquery", "1.2.6"); google.setOnLoadCallback(function() { // Your code goes here. }); </script>Or, you can just include a direct reference like this...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
2. Use a cheat sheet
Not just a jQuery tip, there are some great cheat sheets out there for most languages. It's handy having every function on a printable A4 sheet for reference and luckily these guys have produced a couple of nice ones.http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/
http://colorcharge.com/jquery/
3. Combine all your scripts and minify them
OK, a general JavaScript tip here. But any big project that uses lots of jQuery probably uses lots of plugins (this site uses easing, localScroll, lightbox and preload) so it's usually applicable.Browsers can't load scripts concurrently (well, most can't, yet), which means that if you've got several scripts downloading one at a time then you're really slowing down the loading of your page. So, assuming the scrips are being loaded on every page then you should consider combining them into one long script before deploying.
Some of the plugins will already be minified, but you should consider packing your scripts and any that aren't already. It only takes a few seconds. I'm personally a fan of Packer by Dean Edwards
4. Use Firebug's excellent console logging facilities
If you haven't already installed Firebug then you really should. Aside from many other useful features such as allowing you to inspect http traffic and find problems with your CSS it has excellent logging commands that allow you to easily debug your scripts.Here's a full explanation of all of it's features
My favourite features are "console.info", which you can use to just dump messages and variables to the screen without having to use alert boxes and "console.time" which allows you to easily set up a timer to wrap a bunch of code and see how long it takes. They're all really easy to use too...
console.time('create list'); for (i = 0; i < 1000; i++) { var myList = $('.myList'); myList.append('This is list item ' + i); } console.timeEnd('create list');
In this instance I've deliberately written some very inefficient code! In the next few tips I'll show you how we can use the timer to show some improvements which can be made.
5. Keep selection operations to a minimum by caching
jQuery selectors are awesome. They make selecting any element on the page incredibly simple, but internally they have to do a fair amount of work and if you go mad with them you might find things starting to get pretty slow.If you're selecting the same element time and time again (in a loop for example) then you can just select it once and keep it in memory while you manipulate it to your heart's content. Take the following example where we add items to an unordered list using a loop.
for (i = 0; i < 1000; i++) { var myList = $('.myList'); myList.append('This is list item ' + i); }That takes 1066 milliseconds on my PC in Firefox 3 (imagine how long it would IE6!), which is pretty slow in JavaScript terms. Now take a look at the following code where we use the selector just once.
var myList = $('.myList'); for (i = 0; i < 1000; i++) { myList.append('This is list item ' + i); }That only takes 224 milliseconds, more than 4x faster, just by moving one line of code.
6. Keep DOM manipulation to a minimum
We can make the code from the previous tip even faster by cutting down on the number of times we insert into the DOM. DOM insertion operations like .append() .prepend() .after() and .wrap() are relatively costly and performing lots of them can really slow things down.All we need to do is use string concatenation to build the list and then use a single function to add them to your unordered list like .html() is much quicker. Take the following example...
var myList = $('#myList'); for (i=0; i<1000; i++){ myList.append('This is list item ' + i); }
On my PC that takes 216 milliseconds , just over a 1/5th of a second, but if we build the list items as a string first and use the HTML method to do the insert, like this....
var myList = $('.myList'); var myListItems = ''; for (i = 0; i < 1000; i++) { myListItems += '<li>This is list item ' + i + '</li>'; } myList.html(myListItems);That takes 185 milliseconds, not much quicker but that's another 31 milliseconds off the time.
7. Wrap everything in a single element when doing any kind of DOM insertion
OK, don't ask me why this one works (I'm sure a more experienced coder will explain).In our last example we inserted 1000 list items into an unordered list using the .html() method. If we had have wrapped them in the UL tag before doing the insert and inserted the completed UL into another tag (a DIV) then we're effectively only inserting 1 tag, not 1000, which seems to be much quicker. Like this...
var myList = $('.myList'); var myListItems = '<ul>'; for (i = 0; i < 1000; i++) { myListItems += '<li>This is list item ' + i + '</li>'; } myListItems += '</ul>'; myList.html(myListItems);The time is now only 19 milliseconds, a massive improvement, 50x faster than our first example.
8. Use IDs instead of classes wherever possible
jQuery makes selecting DOM elements using classes as easy as selecting elements by ID used to be, so it's tempting to use classes much more liberally than before. It's still much better to select by ID though because jQuery uses the browser's native method (getElementByID) to do this and doesn't have to do any of it's own DOM traversal, which is much faster. How much faster? Let's find out.I'll use the previous example and adapt it so each LI we create has a unique class added to it. Then I'll loop through and select each one once.
// Create our list var myList = $('.myList'); var myListItems = '<ul>'; for (i = 0; i < 1000; i++) { myListItems += '<li class="listItem' + i + '">This is a list item</li>'; } myListItems += '</ul>'; myList.html(myListItems); // Select each item once for (i = 0; i < 1000; i++) { var selectedItem = $('.listItem' + i); }
Just as I thought my browser had hung, it finished, in 5066 milliseconds (over 5 seconds). So i modified the code to give each item an ID instead of a class and then selected them using the ID.
// Create our list var myList = $('.myList'); var myListItems = '<ul>'; for (i = 0; i < 1000; i++) { myListItems += '<li id="listItem' + i + '">This is a list item</li>'; } myListItems += '</ul>'; myList.html(myListItems); // Select each item once for (i = 0; i < 1000; i++) { var selectedItem = $('#listItem' + i); }This time it only took 61 milliseconds. Nearly 100x faster.
9. Give your selectors a context
By default, when you use a selector such as $('.myDiv') the whole of the DOM will be traversed, which depending on the page could be expensive. The jQuery function takes a second parameter when performing a selection.jQuery( expression, context )
By providing a context to the selector, you give it an element to start searching within so that it doesn't have to traverse the whole of the DOM.
To demonstrate this, let's take the first block of code from the tip above. It creates an unordered list with 1000 items, each with an individual class. It then loops through and selects each item once. You'll remember that when selecting by class it took just over 5 seconds to select all 1000 of them using this selector.
var selectedItem = $('#listItem' + i);I then added a context so that it was only running the selector inside the unordered list, like this...
var selectedItem = $('#listItem' + i, $('.myList'));It still took 3818 milliseconds because it's still horribly inefficient, but that's more than a 25% speed increase by making a small modification to a selector.
10. Use chaining properly
One of the coolest things about jQuery is it's ability to chain method calls together. So, for example, if you want to switch the class on an element.$('myDiv').removeClass('off').addClass('on');
If you're anything like me then you probably learned that in your first 5 minutes of reading about jQuery but it goes further than that. Firstly, it still works across line breaks (because jQuery = JavaScript), which means you can write neat code like this...
$('#mypanel') .find('TABLE .firstCol') .removeClass('.firstCol') .css('background' : 'red') .append('<span>This cell is now red</span>');
Making a habit of using chaining automatically helps you to cut down on your selector use too.
But it goes further than that. Let's say that you want to perform several functions on an element but one of the first functions changes the element in some way, like this...
$('#myTable').find('.firstColumn').css('background','red');
We've selected a table, drilled down to find cells with a class of "firstColumn" and coloured them in red.
Let's say we now want to colour all the cells with a class of "lastColumn" blue. Because we've used the find() funciton we've filtered out all the cells that don't have a class of "firstColumn" so we need to use the selector again to get the table element and we can't continue chaining, right? Luckily jQuery has an end() function which actually reverts back to the previous unaltered selection so you can carry on chaining, like this...
$('#myTable') .find('.firstColumn') .css('background','red') .end() .find('.lastColumn') .css('background','blue');
It's also easier than you might think to write your own jQuery function which can chain. All you have to do is write a function which modifies an element and returns it.
$.fn.makeRed = function() { return $(this).css('background', 'red'); } $('#myTable').find('.firstColumn').makeRed().append('hello');How easy was that?
6 comments
The insertion method used in #7 works considerably faster than #6 because the HTML DOM is generally organized as a tree or some derivative data structure which functions similarly. Essentially you've already pruned your tree before doing the insertion, instead of allowing the DOM to re-organize every time you insert an element.
Right said Mike!
Its cheaper to insert single element(DIV) inside DOM instead of multiple smaller elements like UL.
Excellent article!
For
$.fn.makeRed = function() {
return $(this).css('background', 'red');
}
you don't need to wrap the this into $() as it is already a jQuery object, you could easily write:
$.fn.makeRed = function() {
return this.css('background', 'red');
}
awesome post... thanks a lot
Thanks for your tip Poetro!
We would love to hear from you...