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”);
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
$mydiv.setAttribute('class', 'awesome'); //you can convert jQuery objects to DOM nodes using $jqObj
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:
- File Size (the easiest to check!) - if a tooltip plugin is bigger than jQuery source, something is really wrong;
- 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;
- Cross-browsing - Test, at least on IE7, but Chrome, Firefox, Safari and Opera are good ones to try also
- 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!
Thanks some good advice.
I’m glad you liked! And keep coming, we have much more like this to go 😉
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!
Actually it’s just about improving performance (caching is awesome!), but don’t forget to use the local fallback 😉
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.
Nice roundup. Hadn’t used the CDN fallback before but makes good sense.
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 🙂
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.
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.
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 😉
For #6 why is
If you look that the jQuery code, addClass is running a lot of code that can be done with simply setAttribute
To be fair the equivalent in jQuery would actually be
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.
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 🙂
Luke has sent us this infographic
As you can see, it can be a big difference.. Every second (maybe millisecond depending on your market) counts for conversion!
That infographic is misleading.
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).
Anon got it 🙂
Ol’ js is just unbeatable when it comes to performance.
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.
nice tips. very useful 🙂
Great list, isn’t more secure self-hosting jQuery on my server instead of Google one (i can cantrol server-downtime)?
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.
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)
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.
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
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.
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.
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.
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 🙂
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().
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!
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.
Great advice here.
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.
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..
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.
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 🙂
Thanks some good and very useful tips…
Great tips… thanks 🙂
Good tips jQuery Developer !!!
Very Amazing jQuery Tutorial, I am very thanks for such an useful tips ,trick and information
Regarding #9… one reason not to use CSS without jQuery is lack of support for transitions in with Internet Explorer
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..
Actually it’s supported in IE9 and 10+
vs. using the latest version:
That is the latest release in the 1.7 branch, automatically updated 😉 (…/1/jquery.min.js works too)
Hey Armin, that’s a good tip also!
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
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.
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 🙂
Great tips! Our custom sites are loaded with jQuery, and I wasn’t even aware of half of these issues.
I’m glad I could help. And keep coming, we have much more great content already 😉
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/
I’ve read it once but completely forgotten. Thanks a lot 🙂
Doesn’t #5 eliminate the reason for using #4?
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.
You’ve chosen a very unfortunate example for number 6, because
… will not work in older IE (versions
So, that’s why it’s called example, right?
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
… or, better, use the equivalent property instead:
$mydiv.id = “myAwesomeDiv”;
In the case of the class attribute, that would be
$mydiv.className = “awesome”;
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.
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.
Nice roundup. Thanks for sharing !!
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!
Number 3 is a great tip I didn’t know, very useful for local development when sometimes you can’t access the net
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.
Great article, Obrigado!