8 jQuery Crimes You Really Shouldn’t Commit

When it comes to jQuery talk, professional developers wanted to make sure it’s well optimized. Yeah jQuery is easy to use but it drives developer crazy about performance optimization. Even a mere mili seconds are diamonds-like that are not affordable to miss.

Below are some jQuery crimes, the word crime not reflect that they are the real errors or mistakes or the code won’t work without them but are important suggestions and improvement for developer to polish their skills. Enjoy the round up of general jQuery crimes that a developer shouldn’t commit. They’re easier to fix and should be adopted as every day coding habit.

8 jQuery Crimes You Really Shouldn't Commit

Crime 1 – Not using Google’s hosted latest jQuery version

Does using jQuery latest version make sense? Yes, it actually do. Make sure to use the CDN-hosted copy of latest jQuery version, as every newer version comes with much performance improvement and bug fixed. Currently released version is 1.8.1 and it’s sure that a big number of sites will be still with old version of jQuery.

It’s a good practice that you use a fresher copy every time developing a project, rather using your local copy of outdated jQuery version.

Why it’s preferred to use Google hosted jQuery instead of self-hosted? Hundred thousands of websites are using Google hosted jquery version, which also get cached by browsers. So if any of your visitor already have Google’s jquery file cached, then his browser will catch that same file for your website as well which will ultimately improve your site’s performance. You can copy and paste below snippet to use in your projects.

1
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

 

Note: Noticed the missing http: ? it really look strange at first sight but this crazy protocol-less URL seems to be the best way to indicate to some third party content both via HTTP and HTTPS under Section 4.2 of RFC 3986. And you know the amazing part? it’s supported by all browsers.

 

Crime 2 – Not using Cheat Sheet

Not only for beginners but for pro developers as well, cheat sheets are available for various programming languages and they are pretty helpful if you’re able to get hard copy of them with you while doing some jQuery project. Fortunately you can get them from below.

Crime 3 – Not loading locally for CDN fallback

You might be thinking that what can happen to Google’s CDN who never fails in any near times but it’s a good deal making a backup for fallback as uncertainty is still involved. Use the below snippet to make a fallback as if Google CDN version of jQuery fails, your locally version will be used instead.

1
2
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.8.1.min.js"><\/script>')</script>

 

Another benefit is that when you’re working on client’s project at localhost and you suddenly lost the internet connection, your self-hosted jQuery will be used to make things work. Similarly, Google is blocked in some ISPs so it’s safe to use such way to protect your project from being ruined.

 

Crime 4: Repeatedly using jQuery selectors

One should use the approach of chaining the elements rather calling them over and over again. It helps in performing the operations in a proper sequence and help to reduce the redundancy in writing. Check the below usage approaches.

Wrong Approach:

1
2
3
$("#mySmashingID").css("color", "pink");
$("#mySmashingID").css("font", "Verdana");
$("#mySmashingID").text("Some error message goes here!");

Better Way:

1
$("#mySmashingID").css({ "color": "pink", "font": "Verdana"}).text("Some error message goes here!!");

 

Crime 5 – Not caching stuff properly

This one is the way important and is very effective when considering perfomance and speed elements. Whenever calling any element twice, it’s better to cache it mostly when working with chain elements. You save the selector in a variable and remove the process of calling that same element again and again. Just indicate the variable and jquery will not go through long DOM tree to find your requested element. Below snippet may help.

Wrong Approach:

1
2
3
4
$(‘#mySmashingGag’).appendTo(‘#mysidebar’);
$(‘#mySmashingGag’).addClass(‘widget’);
$(‘#mySmashingGag’).hide();
$(‘#mySmashingGag’).fadeIn(‘fast’);

Better Way:

1
2
3
4
5
var mySmashingGag = $(‘#mySmashingGag’);
mySmashingGag.appendTo(‘#mysidebar’);
mySmashingGag.addClass(‘widget’);
mySmashingGag.hide();
mySmashingGag.fadeIn(‘fast’);

 

Crime 6 – Use ID wherever possible instead of classes

If we use the ID instead of Classes, it will make the processing fast by 100x. jQuery use the native browser method getElementByID so instead of going through many DOM, the thing will be done way faster.

Wrong Approach:

1
2
3
4
// Selecting each item at once
for (i = 0; i < 900; i++) {
var selectedItem = $('.mySmashingItem' + i);
}

Better Way:

1
2
3
4
// Selecting each item at once
for (i = 0; i < 900; i++) {
var selectedItem = $('#mySmashingItem' + i);
}

Moving next, a smart way of ID optimization can be as below

1
$('#foo div.bar')

Optimized will be:

1
$('#foo').find('div.bar')

 

Crime 7 – Smart shorthand for the ready event

Although not the bigger one tip but to help you not only save characters but to know things differently. What can you use as a shorthand of $(document).ready function? Look at the below demonstration.

Normal Usage

1
2
3
$(document).ready(function (){
// your awesome code here
});

Can also be used as

1
2
3
$(function (){
// your awesome code here
});

 

Crime 8 – Using context in the selectors

Providing context is better way to help jQuery. Instead it will have to traversed into whole DOM which may be expensive depending on the page. jQuery selector context are considered a good thing as it will give the narrow context. One benefit we’ll be getting is speed and the other is the logic of solution or behavior.

1
2
$(‘.mySmashingGag’)
.on(‘click’, showMenu);

Better way:

1
2
$(‘.mySmashingGag’, ‘#mySidebar’)
.on(‘click’, showMenu);
1
2
$(‘#mySmashingGag’).find(‘.myWidget’)
.on(‘click’, showMenu);

 

So, It’s Your Turn!

You liked the list? Do you think some other points should be in the list? Speak your mind and share the ideas.


About the author

With a passion for Knowledge, Smashinghub has been created to explore things like Free Resources For Designers, Photographers, Web Developers and Inspiration.

Twitter Visit author website

Subscribe to Smashing Hub


17 Comments

  1. Ady says:

    Crime #9 could be not carefully picking elements to attach binding events consider this HTML

    item one
    item two
    item three
    …….

    and let’s say we want to listen to a click on the list item, the tendency would be to have something like
    var listItems = $(“#list”).find(“li”).on(“click”, function(evt){});
    while a good option it is listening for one event type on many targets rather than listening on one event type on one target and finding the corresponding list item, look at the option below:
    var tList = $(“#list);
    tList.on(“click”, function(evt) {
    var thisLi = $(evt.target);
    // now you have access to all the list item property via thisLi
    // since it has been turned into a jquery object
    });
    Just another way of looking at event binding and oh don’t forget to unbind the event if you do not need it anymore and free up some resources.
    Cheers :)

  2. One thing I do not see, is scoping. I think that it is absolutely important to get into the habit of scoping the jQuery into $

    jQuery(function($){
    //use $ normally
    });

    This always makes sure your jQuery code is no-conflict ready.

  3. leonel says:

    Crime 1 is telling google all the people that use your app by using jquery hosted on google

    please!! jquery is small enough that you can host it on your home server

  4. Michael Berger says:

    Crime 7 violates the “Code should be self-documenting” adage. I much prefer the long form because the “ready” function tells you what it does.

  5. rasel says:

    like all the jQuery……………

  6. A-Webagentur says:

    A tip for “Crime 1″:
    Leaving out the specific version takes the latest version.

    So instead of using:
    //ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js

    Use this:
    //ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

    Did you get it?
    Just “/1/” takes the latest version 1.x.x

    • emmanuel says:

      @A-Webagentur sometimes, if you have to add scripts in old files which contains functions which using some plugins jQuery that won’t work with new version of jQuery.
      So if you take the last release you may have errors or malfunctions.

      I had a case this afternoon by integrating a tracking script on an old project I wanted to do a little update library.
      But I noticed that some features “not working”.
      Since this project has too dependent, so to limit the damage I have kept the old version of jQuery 1.5.2 :-(

      therefore, uses the latest release with moderation

      best regards

    • Nasir says:

      Exactly, I should have mention this part as well. But It’s a good practice to be version specific. As in newer version your used functions may go depreciated. Agreed with Emmanuel happening!

      Your suggestion is also valuable. In some cases, it’s very helpful to use up-to dated jQuery libraries.

  7. emmanuel says:

    hi !
    great recommendations!

    for Crime 5, isn’t it better to write this ? :

    {{{

    var mySmashingGag = $(‘#mySmashingGag’);
    mySmashingGag.appendTo(‘#mysidebar’).addClass(‘widget’).hide().fadeIn(‘fast’);

    }}}

    best regards

    “whether life exists, it’s for dreaming in the clouds”

    • Nasir says:

      Great pick Emmanuel. It definitely is better way to do and in fact crime 4 says what you have notified that to avoid repeatedly using jQuery selectors.

      What I tried to explain in crime 5 was about to do caching properly only. Lacked Crime 4 :P

  8. alberlau says:

    First item is not crime. Before using new jquery version first of all you should test against it.

  9. Louis Foo says:

    $(‘.span’) is faster than $(‘div.span’) :)

    • Nasir says:

      $(‘div.span’) is telling that not to search every element with a certain class or ID. Instead it will search only Divs hence will be faster.

      And difference will be spotted only if talking about a document with thousands of tags and several different css or jQuery calls.

      • Ady says:

        Maybe a good way to understand this is to understand how do CSS selectors work which is replicated by jQuery actually. CSS reads from left to right so if you write:
        $(“div.span”) in jQuery or div.span{} it will look for all elements that have a class of span ( not the span tag), then look for each element in that pool that is a div, depending on the size of your document very expensive indeed.