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:

  • Adding/removing/updating elements or text nodes in the DOM
  • Hiding an element – display: none; causes reflow and repaint, visibility: hidden; only repaints
  • Updating element attributes and styles

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

  • Make changes to a non-displayed DOM fragment (or apply to a clone and then swap them over)
  • Hide an element before making changes – this will cause 2 reflows but it gives the appearance of being quicker
  • Change class names rather than updating individual styles

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:

  • Your visitor is likely to have the file already cached (this will increase as more developers use this idea)
  • Gets around the browser’s limit for simultaneous downloads from one domain
  • Your overseas users will get the file from a CDN so will load faster

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

4 comments on “Front-end developer essentials – 5 tips for efficient jQuery”

  1. So great for me to see your blog about this kind of knowledge which will makes my codes perform better, and show me a different way to think about what to write, I was always consider about “special efficiency of page performance” only.

  2. Great post! I’ve been using jQuery for a while now, and I’ll admit that performance wasn’t something I thought about at all. I’ll definitely be using these techniques on my future projects! Thanks!

Add your comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>