9 jQuery Mistakes you Shouldn’t Commit

By / Apr 19, 2012 / Tips
shares

jQuery is so easy to use that sometimes we just forget that it’s not CSS. While using CSS, we don’t have to give much thought to performance, because it’s so fast that it’s not worth the effort to optimize it. But when it comes to the real world, jQuery can drive developers crazy with performance issues. Sometimes you lose precious milliseconds without even noticing it. Also, it’s so easy to forget about some functions and we keep using the old (and not-so-good) ones.

Let’s take a look at a few of the most-common-and-easiest-to-fix mistakes while using jQuery in your projects.

1. You aren’t using the latest jQuery version

Each version update means higher performance and several bug fixes. The current stable release is 1.7.2, and I’m pretty sure you know about plenty of sites developed using 1.6 and below. Ok, ok, you can’t just update every old site for every jQuery update (unless your client is paying you to do so) but you should at least start using it for your new projects. So, forget about this local copy and just grab the latest release every time you start a new project.

2. You aren’t using a CDN-hosted copy of jQuery

How many unique visitors you`ve got last month? I bet the number is still under 1 billion, right?
So you’d better use Google’s copy of jQuery instead of yours. If your user still has the cached file of Google’s website (or from many other sites that uses its CDN) his browser will just get the cached version, improving a lot your website’s performance. You can use it by copying & pasting this HTML:



3. You aren’t using a fallback for CDN version

I know I said Google is awesome and stuff, but they can fail. So, every time you rely upon external sources, make sure you have a local fallback. I’ve seen this snippet in the HTML5 boilerplate source code and just found it amazing. You should use it too:





4. You aren’t chaining stuff

While doing common operations, you don’t need to call the element every time you want to manipulate it. If you’re doing several manipulations in a row, use chaining, so jQuery won’t need to get the element twice.

Instead of this:


$(“#mydiv”).hide();
$(“#mydiv”).css(“padding-left”, “50px”);

Use this:


$(“#mydiv”).hide().css(“padding-left”, “50px”);

5. You aren’t caching stuff

This is one of the most important performance tips. If you’ll call an element at least twice, you should cache it. Caching is just saving the jQuery selector in a variable, so when you need to call it again you’ll just reference the variable and jQuery won’t need to search the whole DOM tree again to find your element.


/* you can use it this way because almost every jQuery function returns
the element, so $mydiv will be equal to $(“#mydiv”); also it’s good to
use the $mydiv so you know it’s a jQuery caching var */
 
var $mydiv = $(“#mydiv”).hide();
[.. lot of cool stuff going on here …]
$mydiv.show();

6. You aren’t using pure js

Specially for attributes modification, we have several built in methods to get stuff done with pure javascript. You can even "convert" jQuery objects back to DOM nodes to use them with simpler methods, like this:


$mydiv[0].setAttribute('class', 'awesome'); //you can convert jQuery objects to DOM nodes using $jqObj[0]

7. You aren’t checking plugins before including in your site

You know, jQuery is not the hardest thing in the world to code. But good JS (and jQuery), that is pretty hard. The bad news is that while you aren’t a good programmer, you’ll have to rely on trial and error to find out what is good and what isn’t. A few points you must be aware of while including a plugin in your project:

  1. File Size (the easiest to check!) - if a tooltip plugin is bigger than jQuery source, something is really wrong;
  2. Performance - You can try it with firebug and others. They give you easy to understand charts to you’ll know when something is out of place;
  3. Cross-browsing - Test, at least on IE7, but Chrome, Firefox, Safari and Opera are good ones to try also
  4. Mobile - Don’t forget that everything is getting mobile. See if the plugin works, or at least doesn’t crash your mobile browser

8. You aren’t open to remove jQuery

Sometimes it’s just better to remove it and use simple ol’ CSS. Actually if you want, for instance, an opacity hover, or transition can be done with CSS along with good browser support. And there’s no way jQuery can beat plain CSS.

9. You are using jQuery for server side tasks

I know that masking and validating are good, but don’t rely just on jQuery for those. You need to recheck everything on the server side. That is especially important if you are thinking about using AJAX. Also, make sure everything will work with JS disabled.

So, it’s your turn!

Do you have anything you think should be on this list? Share your thoughts!

About the Author

A web designer and entrepreneur from Itajubá (MG), Brasil. Just loves writing about obscure topics and doing some cool stuff. Get in touch at @roch_br.

66 Comments

  1. Stewart
    April 19, 2012

    Thanks some good advice.

    Reply
    • Rochester
      April 20, 2012

      Hey Stewart,

      I’m glad you liked! And keep coming, we have much more like this to go ;)

      []’s

      Reply
  2. Mybej
    April 19, 2012

    2. You aren’t using a CDN-hosted copy of jQuery
    How about making the jQ framework relative to your page?
    and Also, aside from that are there any more issues or problem not using CDN-hosted?

    Fantastic! Very informative!

    Reply
    • Rochester
      April 20, 2012

      Hi, Mybej!

      Actually it’s just about improving performance (caching is awesome!), but don’t forget to use the local fallback ;)

      []’s

      Reply
    • Vitor Campos
      December 9, 2012

      If you are developing a website for an intranet the jQuery lib should be relative to your web server (or a single web server if you have more than one), avoiding unnecessary roundtrips to the Internet. Keep in mind that (in most cases) LAN is faster than your Internet connection.

      Reply
  3. Guille
    April 19, 2012

    Nice tips!
    Thanks!!

    Reply
  4. Jerome Bohg
    April 19, 2012

    Nice roundup. Hadn’t used the CDN fallback before but makes good sense.

    Reply
    • Rochester
      April 20, 2012

      Hi Jerome,

      That fallback is a great thing actually. Specially here (Brazil) every now and then my Internet connection dies so unless I have a local fallback I can’t even work on local projects :)

      []’s

      Reply
      • Lucas Kauz
        April 24, 2012

        Não sabia que o CDN era uma boa opção, vou começar a utilizar, já começo bem com o fallback… rs
        ‘Specially here (Brazil)’ caramba muito bom o conteúdo, não imaginava que era daqui.

        Reply
      • Dan Wellman
        July 10, 2012

        I gotta say, the local fallback isn’t for when a user’s internet goes down. If the person trying to view your site loses their internet connection, a fallback copy of jQuery local to your web server isn’t going to do anything for them.

        The fallback is for if the CDN you are hosting jQuery from goes down, or times out.

        Reply
        • Browser
          November 22, 2013

          We have applications that are internet and intranet. We make it a habit to use a CDN with a fall back. In case the internet goes down our local users can still use it ;-)

          Reply
  5. Alex
    April 19, 2012

    For #6 why is

    $mydiv[0].setAttribute(‘class’, ‘awesome’);

    better than

    $mydiv.addClass(‘class’, ‘awesome’);

    Reply
    • Alex
      April 19, 2012

      Ops.
      $mydiv.addClass(‘awesome’);

      Reply
      • Anon
        April 19, 2012

        If you look that the jQuery code, addClass is running a lot of code that can be done with simply setAttribute

        Reply
        • Derek
          April 19, 2012

          To be fair the equivalent in jQuery would actually be
          $mydiv.attr(‘class’,'awesome’);

          addClass adds additional classes to your existing class attribute, so more code is needed. I can’t speak to the performance differences between setAttribute and attr though.

          Reply
        • Huda
          April 19, 2012

          IMHO unless you’re running a JS-heavy (I mean REALLY heavy!) website, I guess you don’t care about some extra 0.16sec of exec time… just sayin :)

          Reply
          • Rochester
            April 20, 2012

            Luke has sent us this infographic
            http://luketmillar.com/photos/jQuery%20Performance%20Infographic.jpg

            As you can see, it can be a big difference.. Every second (maybe millisecond depending on your market) counts for conversion!

            []’s

          • keif
            September 13, 2012

            That infographic is misleading.

            Yes, the barebones performance is different, but you forget that jQuery also handles *browser inconsistencies* – so it’s not a matter of “always use jQuery methods” but it’s a matter of knowing when to use plain JavaScript or CSS to make the changes you need.

            And “the benefit of addClass is to not remove other classes that may be there” – you should be planning to account for that – it could be as simple as a check to see if a class is already present, or knowing your code well enough to know that “no other classes should ever be applied” – yeah, I know it’s a “perfect world” dream, but that should always be something you think about – how you are checking to make sure it doesn’t happen and not relying on a library to handle everything for you (… which does kind of go in the face of handling browser inconsistencies, but those are something heavily tested versus *your* code).

            :)

        • Rochester
          April 20, 2012

          Anon got it :)

          Ol’ js is just unbeatable when it comes to performance.

          []’s

          Reply
        • Joe Enos
          April 22, 2012

          For adding classes, I think 9 times out of 10, addClass is worth the expense, since it ensures that you’re not removing a class that’s already there. Lots of applications and frameworks add classes to elements that you may or may not even be aware of at design time, whether it’s for styling or functionality purposes. If you simply overwrite the class attribute on an element, you’re removing the classes that are already there, which can be anything from a simple styling problem to a major functionality issue.

          If you’re micro-optimizing, and 100% certain of what you’re doing and that you’ll never have any other classes attached to an element, then go ahead and set the attribute directly. Otherwise, I’d stick with addClass and removeClass.

          Reply
  6. nilambar
    April 19, 2012

    nice tips. very useful :-)

    Reply
  7. Davide De Maestri
    April 19, 2012

    Great list, isn’t more secure self-hosting jQuery on my server instead of Google one (i can cantrol server-downtime)?

    Reply
    • Rochester
      April 20, 2012

      Hi Davide,

      That’s why we got that #3. The best thing actually is when you have a fallback, so you can make use of caching when it’s available and don’t lose functionality when it isn’t.

      []’s

      Reply
      • jochen
        April 20, 2012

        well, regarding security it is acceptable to disregard #3. Server downtime put aside, but if the cdn hosted version _is_ available, /but/ compromised, it is a serious security issue.

        So, I wouldn’t agree on #2 (thus, #3 is the only sensitive way to do it – if you are caring about security, though)

        Reply
        • James
          June 4, 2012

          It’s far more likely that your own site will be compromised than will Google’s, so their copy is actually less likely to be tampered with.

          But there are always some exceptions, like if letting Google count your visitors would be a competitive issue. Or perhaps your business would be severely harmed by a rogue Google employee publishing a change for 15 minutes before it is noticed.

          Obviously those aren’t concerns for sites in general, considering all the usage of ad networks, social network buttons, third-party analytics, third-party video, etc.

          Reply
  8. NoxArt
    April 19, 2012

    Ad #6 one would need to make sure his/her pure JS implementation is cross-browser safe, which is one of the reasons one uses jQuery instead

    Reply
    • Shingo Tamura
      April 19, 2012

      I agree with NoxArt. Even when you just want to add a class to an element, with jQuery you would only need to call $(selector).addClass(“blah”) but with native JavaScript you would need to check if the string of the class attribute contains the whole word “blah” and then if it doesn’t, append it to the attribute.

      Reply
    • Rochester
      April 20, 2012

      Hi NoxArt!

      Yeah, that’s important also. That’s why we just use it when a really well implemented functionality is available, but either way you can check if the function is there (just like we do for the fallback) and otherwise apply the jQuery alternative.

      []’s

      Reply
      • Landon Springer
        December 10, 2012

        I know this thread is old, but I found it ;)

        One thing I haven’t seen mentioned is the “performance cost” of development time. If I have to track six different fallbacks for something jQuery handles out-of-the-box, that’s far more of a performance cost than a few ms of execution time.

        On a related note, you rarely know what jQuery is doing behind the scenes (true for any abstraction layer), so even the peace of mind is worth using the framework.

        Lastly, performance tweaks (like these) most often should be considered when there’s a clear bottleneck or benchmark objective–something more concrete than “One day when I get slashdotted, I want things to load fast!” Premature optimization is the root of all evil, after all.

        Reply
  9. Jay
    April 19, 2012

    Great article! Here’s one more:

    Reinventing the wheel: Rewriting jQuery effects that are built in already. i.e. animating opacity instead of using fadeIn() fadeOut() etc.

    Reply
    • Rochester
      April 20, 2012

      Hi Jay!

      That’s a nice point indeed. We have a lot of good functions built-in in jQuery that people just don’t use. Maybe I could write a little on this in the near future :)

      []’s

      Reply
    • Henri
      April 25, 2012

      Actually… there are some downsides when you use built in effects. You can’t stop them, you have to queue them and so on.. because they are so universal, they can’t be that flexible :)
      It’s not hard to use animate().

      Reply
  10. Lance
    April 19, 2012

    Agree with number 8 – seen too many sites where Jquery is downloaded for no reason – especially bad on mobile orientated sites – CSS can go a long way to give a site that special magic….

    And also seen far too many occasions where JQuery has been downloaded twice – duh!

    Reply
    • Rochester
      April 20, 2012

      Hi Lance!

      Yeah, people just don’t get the point of performance. Sometimes you can achieve awesome effects with simple CSS rules (of course ditching IE6, maybe IE7).

      And about downloading jQuery twice.. haha crazy things we see out there in the internets.

      []’s

      Reply
  11. Luke
    April 19, 2012

    Great advice here.

    One of the problems that I’ve run into with jQuery is that operations that seem innocent may be really slow in jQuery. I ran some performance tests on some of the commonly used jQuery methods and compared them against the native javascript methods.

    Results here: http://luketmillar.com/photos/jQuery%20Performance%20Infographic.jpg

    jQuery is an awesome tool for improving development speed and maintainability, but you still need to be careful about how you use it and the performance effects of the methods you use.

    Reply
    • Rochester
      April 20, 2012

      Hey Luke!

      And you measured things on Chrome. You can imagine how awesome those performance improvements will look in mobile devices or IEs..

      Anyway, jQuery team is improving but we still need to know at least the JS basics for now..

      []’s

      Reply
  12. Tony Green
    April 19, 2012

    Thank you for the fallback tip. This is something I’ve been looking for for ages, because I’ve seen my sites go tits-up on the odd occasions where Google stopped serving JQuery for whatever reason.

    Reply
    • Rochester
      April 20, 2012

      Hi Tony!

      You’re welcome! I’ve seen Google stopping to serve CDN content a few times in my life, but I really don’t want to lose functionality because of such a simple issue :)

      []’s

      Reply
  13. web designer
    April 20, 2012

    Thanks some good and very useful tips…

    Reply
  14. Mustified
    April 20, 2012

    Great tips… thanks :)

    Reply
  15. Narendra
    April 20, 2012

    Good tips jQuery Developer !!!
    Thanks !!!

    Reply
  16. ddmagstuff
    April 20, 2012

    Very Amazing jQuery Tutorial, I am very thanks for such an useful tips ,trick and information

    Reply
  17. Synthetic Tone
    April 20, 2012

    Regarding #9… one reason not to use CSS without jQuery is lack of support for transitions in with Internet Explorer

    Reply
    • Rochester
      April 20, 2012

      Hi Synthetic Tone,

      Sure, there is a lot of cool stuff you just can’t do with IE. But alpha, rgba, shadows and a few more is possible.. You know, it’s more about a mindset, check if you can do things with pure CSS and after that you go with jQuery..

      Thanks!

      []’s

      Reply
    • Shane
      April 20, 2012

      Actually it’s supported in IE9 and 10+

      Reply
  18. Armin
    April 20, 2012

    vs. using the latest version:
    //ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js

    That is the latest release in the 1.7 branch, automatically updated ;) (…/1/jquery.min.js works too)

    Reply
    • Rochester
      April 20, 2012

      Hey Armin, that’s a good tip also!

      Thanks!

      []’s

      Reply
    • Eddie Monge
      April 20, 2012

      You don’t want to do that as the cache life on isnt as long as the specific version:
      Extremely short cache life: //ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
      Short cache life: //ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js
      One year cache life //ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js

      Reply
  19. Prinzhorn
    April 20, 2012

    I don’t fully agree on 2 and 3. I already had a situation where the Google Server took 10 seconds to respond which ultimately means your users are seeing a blank page because the request blocks rendering. Your fallback doesn’t help at all in such situations. Be careful when introducing external dependencies.

    Reply
    • Rochester
      April 25, 2012

      Hi Prinzhorn,

      That’s a good point, I didn’t realize it. I’ll think abut a better solution then, and probably will come with a new jq post, thanks for letting me know :)

      []’s

      Reply
  20. SavorWeb
    April 20, 2012

    Great tips! Our custom sites are loaded with jQuery, and I wasn’t even aware of half of these issues.

    Reply
    • Rochester
      April 25, 2012

      Hi SavorWeb,

      I’m glad I could help. And keep coming, we have much more great content already ;)

      []’s

      Reply
  21. Nick Gassmann
    April 20, 2012

    I know you’re from Brazil, so I’ll turn my grammar phasers to stun. :) Specially or especially: http://www.dailywritingtips.com/especially-vs-specially/

    Reply
    • Rochester
      April 25, 2012

      Hi Nick!

      I’ve read it once but completely forgotten. Thanks a lot :)

      []’s

      Reply
  22. Joshua Abbott
    April 20, 2012

    Doesn’t #5 eliminate the reason for using #4?

    Reply
    • Rochester
      April 25, 2012

      Oh no, you should use them both.

      Of course caching will improve your code, but you’d better use chaining also, if you don’t need to cache an item, for instance.

      []’s

      Reply
  23. Tim Down
    April 20, 2012

    You’ve chosen a very unfortunate example for number 6, because

    $mydiv[0].setAttribute(‘class’, ‘awesome’);

    … will not work in older IE (versions

    Reply
    • Rochester
      April 25, 2012

      Hi Tim!

      So, that’s why it’s called example, right?

      []’s

      Reply
      • Tim Down
        May 30, 2013

        Not quite sure what you’re saying. It’s certainly an example but unfortunately a bad one. Either pick an attribute that will work with old IE’s broken setAttribute() implementation, such as

        $mydiv[0].setAttribute(“id”, “myAwesomeDiv”);

        … or, better, use the equivalent property instead:

        $mydiv[0].id = “myAwesomeDiv”;

        In the case of the class attribute, that would be

        $mydiv[0].className = “awesome”;

        Reply
  24. Alex
    April 20, 2012

    Very good advices about jquery. In advice no 8, although many things can be done with css, there may be cross browsers problems so it’s best to use a framework to do that stuff.

    Reply
    • Rochester
      April 25, 2012

      Hi Alex!

      Sure, but there are plenty of things that can be done with a few lines of code. But all depends on your need, of course.

      []’s

      Reply
  25. Vivek Dhande
    April 21, 2012

    Nice roundup. Thanks for sharing !!

    Reply
  26. Parag
    May 3, 2012

    Good compilation indeed! I would like to add some points ( some of it might already be partially covered in article/comment)

    -jQuery plugins should be avoided as much as possible. Most of e time they are amateur and although they appear to be saving lots of time during initial development, they can be nightmare during enhancements and bug fixing, especially if we care for absolute perfection.

    - jQuery makes events and Ajax calling pretty easy and fun. One should be cautious about not using features/parameters which are not really required. Things can get really ugly and complex if not done properly.

    - Remeber jquery has bugs too!

    Reply
  27. tinny
    June 22, 2012

    Number 3 is a great tip I didn’t know, very useful for local development when sometimes you can’t access the net

    Reply
  28. Daniel Rosca
    April 22, 2013

    Luckily, with the new jQuery release (2.0) there is no more need to offer support for IE6, 7 or 8 as jQuery 2.0 doesn’t support those browsers anymore. Thank you for these useful tips.

    Reply
  29. Guy
    August 26, 2013

    Great article, Obrigado!

    Reply

Leave a Reply