Front-end developer essentials – 5 tips for efficient jQuery

Over the last few months I’d like to think my skills in jQuery have got a lot better, I’ve been using it everyday and for more than just showing and hiding areas of a page. Along the way I’ve read about a few ways in which you can make your code a bit more efficient.

1. Use variables to cache multi-use DOM values or collections

The place I use this most is when using $(this) within event handlers. When I started I read somewhere that any variable assigned to a DOM element should be prefixed with a dollar, so you’d write:

$this = $(this);

or:

$foodItem = $('#shopping-list li');

$foodItem.click(function() {
   ... do something ...
});

Some people see this as an ugly way of writing code. It’s obviously up to you how you name your variables, the idea of caching is more important than the name.

2. Minimise the effects of reflow

The second way is to think about what parts of your code will trigger a reflow. Reflow is expensive, it is the equivalent of laying out the whole page again. The main items that trigger a reflow are:

You can minimise the effect of reflow in the following ways:

3. Make use of chaining

You’ll probably have made use of chaining in removing a certain class to add another in its place. So instead of referencing the #element twice you can chain functions together:

$('#element').removeClass('hidden').addClass('expanded');

Chaining allows you to invoke multiple functions from one selector. A bonus is that it can aid code readability if you use a new line for each function:

$('#element')
    .removeClass('hidden')
    .addClass('expanded')
    .find('li.foo')
        .append('This is visible')
        .attr('aria-expanded', 'true')
.end()
    .find('li.bar')
        .remove();

Using end() will end the most recent filtering operation and return to the original set of matched elements – in this case #element.

4. Use multiple selectors

This is for instances where you’d like to call the same function on a number of selectors, so instead of:

$('form p').addClass('valid');
$('form li').addClass('valid');
$('form span').addClass('valid');

You can pass all 3 in one go:

$('form p, form li, form span').addClass('valid');

5. Use a CDN to host your library

Instead of hosting jQuery on your own server, use a CDN like that provided by Google.

<script src="http://ajax.googleapis.com
            /ajax/libs/jquery/1.4.2/jquery.min.js"></script>

The advantages are:

You can even get fancy and fall-back to your own hosted file if Google’s is not available – I’ll leave that as a homework exercise.

Also in the “Front-end developer essentials” series

Further reading