Helpful jQuery Tricks, Notes, and Best Practices Part I
12.16.2011   |   1comment

If there is one bad thing about jQuery, it’s that the entry level is so amazingly low, that it tends to attract those who haven’t an ounce of JavaScript knowledge. Now, on one hand, this is fantastic. However, on the flip side, it also results in a smattering of, quite frankly, disgustingly bad code (no one is immune to this). But that’s okay; frighteningly poor code that would even make your grandmother gasp is a rite of passage. The key is to climb over the hill, and that’s what we’ll discuss today.

Methods Return the jQuery Object
It’s important to remember that most methods will return the jQuery object. This is extremely helpful, and allows for the chaining functionality that we use so often.

$someDiv
.attr('class', 'someClass')
.hide()
.html('new stuff');

Knowing that the jQuery object is always returned, we can use this to remove superfluous code at times. For example, consider the following code:

var someDiv = $('#someDiv');
someDiv.hide();

The reason why we “cache” the location of the someDiv element is to limit the number of times that we have to traverse the DOM for this element to once. The code above is perfectly fine; however, you could just as easily combine the two lines into one, while achieving the same outcome.

var someDiv = $('#someDiv').hide();

This way, we still hide the someDiv element, but the method also, as we learned, returns the jQuery object — which is then referenced via the someDiv variable.

The Find Selector
As long as your selectors aren’t ridiculously poor, jQuery does a fantastic job of optimizing them as best as possible, and you generally don’t need to worry too much about them. However, with that said, there are a handful of improvements you can make that will slightly improve your script’s performance. One such solution is to use the find() method, when possible.

// Fine in modern browsers, though Sizzle does begin "running"
$('#someDiv p.someClass').hide();

// Better for all browsers, and Sizzle never inits.
$('#someDiv').find('p.someClass').hide();

The latest modern browsers have support for QuerySelectorAll, which allows you to pass CSS-like selectors, without the need for jQuery. jQuery itself checks for this function as well. However, older browsers, namely IE6/IE7, understandably don’t provide support. What this means is that these more complicated selectors trigger jQuery’s full Sizzle engine, which, though brilliant, does come along with a bit more overhead. Sizzle is a brilliant mass of code that I may never understand. However, in a sentence, it first takes your selector and turns it into an “array” composed of each component of your selector.

// Rough idea of how it works
['#someDiv, 'p'];

It then, from right to left, begins deciphering each item with regular expressions. What this also means is that the right-most part of your selector should be as specific as possible – for instance, an id or tag name.

Bottom line, when possible:

  • Keep your selectors simple
  • Utilize the find() method. This way, rather than using Sizzle, we can continue using the browser’s native functions.
  • When using Sizzle, optimize the right-most part of your selector as much as possible.

Context instead?
It’s also possible to add a context to your selectors, such as:

$('.someElements', '#someContainer').hide();

This code directs jQuery to wrap a collection of all the elements with a class of someElements – that are children of someContainer – within jQuery. Using a context is a helpful way to limit DOM traversal, though, behind the scenes, jQuery is using the find method instead.

$('#someContainer')
.find('.someElements')
.hide();

I hope this first installment has been useful to someone out there in the interweb, and if not, maybe my next few will be!

Tags: ,

One Comment

  1. Benjam says:

    Awesome tips about the selectors.
    A few notes for further improvements in speed…
    When selecting elements with a particular class and you only need a specific type of element, its faster to include that element in the selector:
    $(‘a.external’) is much faster than $(‘.external’) because it only has to look at all the As instead of every element on the page.

    Also, when I store a jQuery object, I prefix it with ‘$’ so I know it’s a jQuery object:
    var $elem = $(‘#foo’).hide( );

Leave a Comment