12 Tips to improve your jQuery code
jQuery is a library that greatly simplifies how developers use JavaScript. The tips below aim to point out some advanced tricks that can be used with jQuery code to make it more efficient:
1. Load jQuery from the Google AJAX Libraries
There are several advantages to loading jQuery from the Google AJAX Libraries, including:
- Saving bandwidth (every little bit matters)
- Speeding up loading times (if a visitor has already visited a website that loads jQuery from the Google AJAX Libraries, it will be cached on their machine)
To load the library from the Google AJAX Libraries, you can use Google’s AJAX Library API:
<script src="http://www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript"> google.load("jquery", "1.3.2"); google.setOnLoadCallback(function() { //add your jQuery code here }); </script>
… or you can include the library directly:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
2. Combine and minify your script files
Combining and minifying your jQuery (and other JavaScript) code results in performance increases due to the smaller amount of script files that need to be loaded and the reduced filesizes.
There are several free tools available to minify jQuery code, with some of the most popular ones being JSMin, jsobf, and the YUI Compressor.
3. Use Firebug’s logging functionality
In addition to its HTML and CSS inspection functionality, the Firebug plugin for Firefox allows the use of several console logging methods that make debugging your scripts easier:
Console Logging:
Use the console.log(object[, object, ...]) method to record debugging information. The first argument to log may be a string containing printf-like string substitution patterns:
function consoleLog() { console.log('The consoleLog() function was called %d times by %s.', callCount, callUser); console.log('The consoleLog() function was called', callCount, 'times by', callUser); }
Logged objects will be written to the console as interactive hyperlinks to inspect the object in Firebug’s HTML, CSS, Script, or DOM tabs.
String substitution patterns:
- %s – String
- %d / %i – Integer
- %f – Floating point number
- %o – Object hyperlink
Console Error Messages:
Use the console.info(object[, object, ...]), console.debug(object[, object, ...]), console.warn(object[, object, ...]), and console.error(object[, object, ...]) methods to record different levels of error messages:
function consoleErrors() { console.info('This is an info message.'); console.debug('This is a debug message.'); console.warn('This is a warning messages.'); console.error('This is an error message.'); }
Console Timer Logging:
Use the console.time(name) and console.timeEnd(name) methods to record intervals:
function consoleIntervals() { console.time('Geekology Timer'); for(x=0; x < 9999; x++) {} console.timeEnd('Geekology Timer'); }
Console Assertions:
Use the console.assert(expression[, object, ...]) method to test if an expression is true, if not a message will be written to the console and an exception thrown.
Console Property Listing:
Use the console.dir(object) and console.dirxml(node) methods to print an interactive listing of all properties of an object (console.dir(object)) or the XML source tree of an HTML or XML element (console.dirxml(node)) to the console.
Console Tracing:
Use the console.trace() method to print an interactive stack trace of JavaScript execution at the point where it is called. The stack trace details the functions on the stack as well as the values that were passed as arguments to each function.
Console Message Grouping:
Use the console.group(object[, object, ...]) method to write a message to the console and nest future messages until the console.groupEnd() method is called.
The console.groupCollapsed(object[, object, ...]) method performs the same function as the console.group(object[, object, ...]) method, except that the message block is initially collapsed.
Console Profiling:
Use the console.profile([title]) method to turn on and the console.profileEnd() method to turn off Firebug’s JavaScript Profiler.
Console Counting:
Use the console.count([title]) method to write the number of times that the line of code where count was called was executed.
4. Keep selector operations to a minimum
Rather than letting your code select the same element repeatedly (for example, in a loop), simply select it once and keep it in memory to manipulate it later:
var messageBox = $('.messageBox'); for (i=0; i < 100; i++) { messageBox.append('<p>This is test message #' + i + '.</p>'); }
5. Keep DOM manipulation to a minimum
DOM manipulation is one of the slowest operations JavaScript (and hence, jQuery) can perform. Rather than using $().append(), $().prepend(), $().after(), $().wrap() and $().html() multiple times, try to combine the content and call one of the abovementioned functions once:
var messageBox = $('.messageBox'); var message = ''; for (i=0; i < 100; i++) { message += '<p>This is test message #' + i + '.</p>'; } messageBox.html(message);
6. Use IDs instead of classes in selectors
When selecting elements by ID jQuery uses the browser’s native getElementById() method, whereas selecting elements by class requires that jQuery perform its own DOM traversal.
7. Give selectors a context
When using selectors like $(‘.messageBox’), the entire DOM is traversed to find the element. Providing a context to the selector will tell it to only traverse the specified context:
var messageBox = $('.messageBox', $('#sidebar'));
8. Use chaining properly
When you need to perform multiple methods on elements, jQuery can chain those methods together. To make these chains more readable, you should use line breaks:
$('.messageBox').css('background', 'red') .show();
If you selected a node within the original selection during the chain but you want to run a method on the original selection afterwards, you can use jQuery’s $().end() method:
$('.messageBox').find('.icon') .css('background', 'red') .end() .show();
8. Use event delegation
When attaching events to multiple elements, event delegation can be used to attach just s single event to the elements’ parent, then have the event handler perform certain actions on the actual element that triggered the event.
An example of this would be a table with 10 columns and 10 rows, totalling 100 cells. Instead of attaching a $().click() event to 100 cells, you could attach the $().click() event to the table and have the event handler figure out which cell triggered the event:
$('.resultsTable').click(function(e) { var clickedElement = $(e.target); clickedElement.css('color', 'green'); });
9. Store states with jQuery’s data() method
jQuery has a $().data() method that can store data in key / value pairs against any element:
$('.messageBox').data('origin', 'notifications'); $('.messageBox').data('status', 'displayed');
The $().removeData(elem) and $().removeData(elem, name) methods can be used to remove all or a specific data item from elements.
10. Use custom selectors:
When one of jQuery’s built-in selectors for ID, class, tag, attribute, etc. doesn’t cater to your needs, you can add custom selectors. For example, if you needed a selector to find images larger than 100px by 100px:
$.extend($.expr[':'], { nonThumbnail: function(a) { if (($(a).height() > 100) && ($(a).width() > 100)) { return true; } return false; } }); $('.image:nonThumbnail').hide();
11. Use jQuery’s noConflict() method to rename the jQuery object when working with multiple frameworks:
Many JavaScript frameworks use the “$” symbol to reference the framework. If you use multiple frameworks in your project, use the jQuery.noConflict() method to release the “$” object and assign jQuery to a custom-named object:
var jQ = jQuery.noConflict(); jQ('.messageBox').hide();
12. Use shorthand for the $(document).ready() event:
Instead of writing out the $(document).ready() event:
$(document).ready(function (){ alert('Hey!'); });
… rather use its shorthand version:
$(function (){ alert('Hey!'); });
Related posts:
- Subdomain tracking update to the geekGa.js jQuery plugin for Google Analytics
- Speeding up Google Analytics load times with a jQuery plugin
- Minify JavaScript code to obfuscate details and decrease load times
- Google’s Page Speed Firefox plugin
- Disabling auto-formatting of telephone numbers by the Skype Browser Plugin



29 Oct 2009 








author
you (accidentially, i assume) set your script src to “code.google.com/apis/ajaxlibs/documentation/” under pt. 1
Oops, thanks for pointing that out!
I’ve corrected the URL now.
I’m not a huge fan of google for hosting libraries I use … and to minimize the number of script tags in the page I’ve been using a global.js script for a while, containing jQuery, sizzle.js and all the js stuff I need inside with the document.ready on the bottom of the global.js … So I don’t like minified scripts either …
:p
But very good post, thx.
@edouard Hosting libraries elsewhere is a trust issue, but since so many people use the Google AJAX libraries I feel it should be safe to include my libraries from there.
As for combining and minifying scripts, I quite like the idea of having them raw on a development server but minified and combined on a live system – in addition to the slight speed increase and other benefits, it seems neater.
Good tips! There’s a typo in your explanation of Firebug API – s/console.asset/console.assert/
Thanks Adam! I’ve now corrected it.
Great set of tips, thanks for posting!
Also, #6 is less relevant now because all the modern web browsers have native support for getElementsByClassName.