10 easy and useful ways to improve your jQuery coding and performance

Lists like this have been done and re-done so many times. The list I’ve put together is based on a combination of things others have taught me, I’ve tried to implement myself based on the good ol’ interweb or self taught over time. Google can be your best friend or worst enemy (keep Safe Search on!).

The tips below are easy enough to implement, are not rocket science and are in no particular order, however they are designed to help you improve your technique and speed up how a browser processes your code;

1. Always Use the Latest Version (if possible)

jQuery is in constant development and improvement, so to save yourself having to update your local version loads of times use the following snippet;


Depending on your project environment you may have to roll out with a fixed version. A good point to note.

2 . Use For instead of Each

This was someone by the name of Jon Banner (a good ol’ mate of mine and former colleague) who told me this. After helping me write some code (about 4+ years ago).

var array = new Array ();  
for (var i=0; i<10000; i++) {  
    array[i] = 0;  
}

There are numerous sources out there at show that for used online is over 100% faster (in milliseconds) as supposed to when Each is used in a loop.

3. Use return false

Ever written a function for an element or group of elements on a page and once clicked the page jumps to the top? This may no doubt become quite annoying if the page is long. so;

$('#element').click(function(){
    // do something...
    return false;
});

4. Compartmentalize your code

For me this has been a lifesaver. If you are building or managing larger sites like I am then you don't want ALL of your JavaScript loaded each time the page (or a specific page template is triggered).

This method is a bit similar to the switch function used in JavaScript or ActionScript, but the difference is you have control over what is called, it's not pre-defined like the switch function.

This in turn lessens the load on the browser reading and activating ALL the functions in your JavaScript file.

var mylib =
{
    primary_functions :
    {
        init : function()
        {
             // Functions go here
        }
    },
    specific_template_functions :
    {
        init : function()
        {
             // Functions go here
        }
    }
}
$(window).load(function(){
    // It's more efficient to load any generic scripts after the HTML has loaded.'
    mylib.primary_functions.init();
});

Your "specific_template_functions" function can be called when that specific template or page is loaded. Doing this for 5 - 10 lines of code is no use but it serves as good practice to anyone wanted to create good habits moving forward by compartmentalizing larger chunks of code.

5. Combine and minify your JavaScript

By the time your site has gone into testing you may realise that you have more than one JavaScript file or plugin referenced on your site. Combine them into one file. It's always faster and good practice to at least combine multiple JavaScript files versus the browser having to load and read multiple files.

6. Avoid manipulation of the DOM

There are several reasons for this, some of those reasons being website accessibility. For example if you "absolutely require" that some text or element is read by a screen reader, if the browser has scripts disabled your up the creek without a paddle, the fat lady has sung, lights out - you get the point. In my experience you use this if your doing something dynamic, adding some garnish to the page, but ultimately you will want to limit this as much as possible.

.append(), .prepend() and .after() (I believe) use up much more resources in terms of time versus .html(). Build what you want to insert before inserting it makes logical sense also. So;

var yourlist = '';  
for (var i=0; i<1000; i++) {  
    yourlist += '
  • '+i+'
  • '; } ('#list').html(yourlist);

    7. Traverse HTML via the correct node identifier

    It is a lot quicker for your script to find an ID rather than a class. No need to show examples here. However if you do want an example shown let me know.

    8. Cheat Sheets

    This is a really good way to ensure that you don't forget the numerous functions available to you when coding. There are several about but some of my personal favourites are;

    9. Load your jQuery at the end of your page

    In short, the code references really should be at the bottom of the page. also if you need to make any calls to your compartmentalized code from within a page you can use the window load function as mentioned above, but is also below for quick reference;

    $(window).load(function() {
        // It's more efficient to load any generic scripts after the HTML has loaded.'
    });
    

    10. Return number of elements in page

    It's a really simple and quick way to find out how many elements are on the page;

    $('element').size();
    

    6 Comments

    1. Right says:

      Howdy
      your code examples show up as black on black (or something very close to that)
      firefox 13.01 osX

    2. STEVER says:

      Didn’t know about “$(‘element’).size();”, thx!

    3. Your code reviewer says:

      how do I Combine and minify your JavaScript?

    4. Your code reviewer says:

      ever heard of a document fragment … no I didn’t think so. Google it maybe…

      • Ah yes, the ability to store small amounts of data in the browser beyond a session. Something not used that much these days, even though it can help with performance a good deal.

        Thanks – I’ll look to make my next set of experiments with DF’s a future post.

    Leave a Reply

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