permalink

20

8 jQuery Performance & Optimization Tips You Need In 2010

per

 

Great topic today!. Performance optimization. Performance optimization is an important aspect of any type of coding project, including those that use jQuery. Today I’m going to go through some quick useful jQuery coding and performance tips that I think are important for every JavaScript developer to bare in mind when writing their projects using the jQuery framework. Some of these are going to be a little obvious whilst others are things that you might not have considered doing before.

Ask yourself this question. Do you think that your scripts are currently running as quickly as they could be?. Do they occupy the smallest filesize footprint and still deliver the same results as their un-optimized counterparts?. The answer to these questions in most cases is ‘no’.

Often in web development we’re working against tight deadlines and can sometimes fall into a pattern of thinking that if our scripts work in all web browsers and aren’t howling alert! help me! that our job is done. The truth is that if we were to all put in just a little bit more effort, we could actually deliver web applications and scripts that are both fully functional and as optimal as they can be.

Today I’m going to give you 8 tips that will help you ensure that your jQuery projects stay optimized.

1. Stay up to date! Are you using methods and techniques that are obsolete?.

      image

When I say obsolete, I mean that there may be better ways to achieving code that you regularly write. The easiest way to find out if this is the case is to ask yourself this question:  Do you know what the differences between jQuery 1.3.2 and jQuery 1.4.2 are?. If not, keep reading!

The jQuery team spend hundreds of combined hours every year churning out new functions and optimizing the existing ones in the jQuery library. Heck, I sometimes question if John Resig even sleeps, such is his dedication to making the library be as efficient as possible.

What this means is that if you’re able to use the latest features and techniques jQuery has to offer that are more optimal that what you’ve been using so far, you can get very cheap, very quick boosts in performance for your application.

We all know that it can be a lot easier just using the jQuery techniques you’re already used to, but if it just takes a few minutes to read through the specs and pick up a few quick performance wins, then why not just do it?

Do you know what all of these do?

Delegate/Undelegate
nextUntil
Chaining event handlers
Controlling a functions context
Does a element have something? (.has)
Element Unwrapping
Determining an object’s type

If not, here are the tutorials and references for the jQuery:

you can also find tons of 1.4.2 snippets in my recent jQuery snippet posts.

 

2. Context-aware jQuery Code Execution – Are you loading code that isn’t needed?

 

There are some developers that will load all of the jQuery code for a site on every page, regardless of whether or not it’s going to be used there or not. (Don’t worry, if you’ve done this before, the good news is you can always change that habit!).

What you need to remember is that jQuery still has to take time to execute that code and if its not needed you can get a quick performance gain by checking whether you’re on a page which requires that script to run.

This can be achieved in many ways such as defining a class or ID unique to each page’s content and checking for it’s existence before you run it’s specific code or even through server-side processing if you want to run check on the filename being accessed.

As long as you can do your best to only load code that’s needed, you’ll get some quick performance boosts that may not have been there if you hadn’t thought about this in advance.

 

3. jQuery Unit Testing

 

        image

How many of you have actually written unit tests for your JavaScript or jQuery code this week?. I’m hearing crickets and one man in the corner saying ‘me’. Uh oh. I think that there’s a tendency for us web developers to  forget that just like Java, C++ or .NET, JavaScript is a programming language equally as capable of having bugs as the others and to minimize this, spend just that extra little bit of time on your project writing some unit tests for your code. It’s really really easy to.

Not only is it good as a software engineering best practice, but it’s also something you need if your code is going into a live production system which could be accessed by a large audience. You want your code to be fully functional and to be structured in such a way that you know exactly how it’s going to behave and can anticipate quirks in advance.

One right off the top of my head is if you’re using Ajax to load up some of your page content. If things are taking a longer to load up than they should, wouldn’t it be nicer if your app output a ‘Connection Issue Detected, please try refreshing’ message rather than just hanging for ages?. Believe me, your users will appreciate your attention to detail.

If you’re looking for some powerful JavaScript unit testing tools, QUnit and FireUnit are both quite useful and I’d recommend checking them out. Nettuts also put out a really straightforward article last year on how to use QUnit to test your jQuery code and I’d recommend giving it a read some time.

4. Benchmark Your jQuery Code

 

            image

How fast is your code? If you’re looking for a simple way to improve the performance of your code, simply log the amount of time it takes for your functions to execute and use that as a starting point for your optimization strategy.

The Firebug console makes it very easy for any JavaScript developer to log debug information in the same way you would with any other language’s IDE so consider using it. Logging might sound very simple, but it can actually turn up quirks in your code you may not have realized existed or which may need optimization.

Now if you’re looking for even more accurate results (remember, Firebug is an add-on and will introduce marginal delays to your stats because it’s GUI needs to be updated dynamically), close Firebug and create your own own simple logging tool as follows (note: this is a very basic example and you’ll need to edit the code as per your needs).

JavaScript

function t() {
    var time = new Date();
    return time.getTime();
}
$(window).load(function() {
    var s = t();
    for (var i=0; i<10000; i=i+1) {
        $('#content').html("hello");
    }
    $('#out').append( (t()-s) +'ms');
});

HTML

Time:
Content:

Benchmarking ensures that you know how fast your code runs, not just in one browser but potentially in all of them. This can be of significant importance when you’re talking about large jQuery applications or apps that rely heavily on JavaScript based animations or Ajax.

 

5. Keep download times to a minimum with one compressed master JS file.

    image

Page-load speeds are an ever increasingly important factor in performance optimization and one only needs to look at Google’s inclusion of this in page rankings to realize just how important decreasing the number of files you need to load is.

How many WordPress, Corporate or Portfolio sites to you visit where if you look at the source code, you’ll see maybe 10 or 12 different JavaScript files that need to be loaded before the page is ready to be used?. If you want your pages to load quicker, just ensure that you use a compression and concatenation tool that will put all your scripts into the same file so you can still update them separately but they’ll be delivered at the same time on your live site. This way you’ll achieve both a smaller JavaScript footprint
and your site only requiring one JS file to download for your code.

(A sidenote with that is, please try to cut down on the number of document.ready and window.load instances in your page. If your code will all be running out of the same file, it probably makes sense to just have one instance of these running).

These resources will help you achieve all of the above and are free whether
you are using a PC or Mac:

http://jscompress.com/ (for any sites)
http://www.halmatferello.com/lab/wp-js/ (for WordPress users)
http://ant.apache.org/manual/CoreTasks/concat.html (for Ant users)  

6. Context Vs. Find

 

It’s true, where possible you should always try to run your selections based on a context however it’s useful just to bare in mind that when you’re passing a context to the jQuery constructor, it creates an extra unnecessary extra function call.

jQuery’s insides run content.find(selector) anyway, so you can technically skip that step if you’re working in a page structure that may not benefit greatly from using context. Below you can see an example of what I’m talking about.

//This is context is typically used.
$('div', context ).doSomethingOrOther();
//But here, you can do the same thing minus the extra
//instance and the additional function call
context.find('div').doSomethingOrOther();

7. Window.load all the way.

 

Document.ready isn’t a terrible thing, but it’s a habit that many developers still have including myself occasionally. It doesn’t matter where you’re using $(function(){}); or the full version of this, but truth be told it is significantly more optimal to be using Window.load in your applications.

The reason behind this idea is that document.ready happens during page render while  objects are still downloading and that cause some stalls in your page. You don’t want that. You can however reduce the CPU utilization during the page load by binding your jQuery functions to  the $(window).load event – it occurs after all objects called by the HTML have fully completed downloading.

That’s one line change that can give you scripts that little extra performance boost!.

8. Strike A Balance Between Your Use Of JavaScript & jQuery

 

jQuery is a fantastic way to speed up work for almost anyone on the front-end. Remember however, that there are scenarios where jQuery may take longer to execute certain functions than if you were to use regular JavaScript. CSS styling is just one example that comes to mind.

Some of the other methods we’re all used to using like show() and hide() also have their own performance overheads so always remember to strike a balance between your code’s complexity and it’s overall efficiency. You can always mix plain JavaScript code with some jQuery and in most cases it should still run fine.

Another situation is this: If all you need to do is run two lines of JavaScript code, there isn’t a need for you to use jQuery (even in it’s minified form it’s still roughly 20-30kb’s worth of extra data that needs to be downloaded).  Similarly, if you’re writing a large complex application try to use jQuery rather than writing overly long plain-JavaScript script.

Use best judgement here and you’ll find that you’ll get the both of both worlds and their combined performance advantages.

 

And that’s it!. If you’ve found this post useful please feel free to share it with your friends and colleagues by clicking the 8 jQuery Performance & Optimization Tips You Need button. Until next time, may the $ be with you.

20 Comments

  1. Pingback: 8 jQuery Performance & Optimization Tips You Need In 2010 … | Source code bank

  2. Someone (I think it was Paul Irish in one of his hawtness episodes) mentioned that we can slow down our use of $.each. Is there a better way to iterate over objects and arrays now in 1.4.2?

    Could you show this?

  3. Nice read. $(window).load, I find works well for carousels etc, so they start only after all the images have loaded, but I find it just as important to have Document.ready additionaly in my scripts as visitors tend to start clicking on stuff while the page is still loading! So , I'd say, use both… wisely!

  4. Pingback: 8 jQuery Performance & Optimization Tips You Need In 2010 | RefreshTheNet

  5. Pingback: links for 2010-05-03 | Folks Pants

  6. Pingback: Linkhub – Woche 17-2010 - pehbehbeh

  7. Pingback: 31 trozos de código de jQuery | Feimstudio - Diseño y programación web

  8. Pingback: Really Useful Tutorials You Should Have Read in May 2010 | PIXEL SHOP

  9. hey, i saw your presentation on html5. you think you can send that to me? and also i want to learn the basics of html and css so that i can create the skeleton of a website by myself (no client side database or any such thing), can you suggest tutorials?

    great work btw.

    • Thanks Modi! If you check out the original HTML5 page presentation page you'll see a download button in the sidebar where you can download the presentation in MP4 format. Hope that helps!

  10. Pingback: Simple tricks to boost website performance | Open Source Code for Web lovers

  11. Pingback: jQuery Performance Tips Cheat Sheet | Dumitru Glavan

Leave a Reply

Required fields are marked *.

*