At the recent CTFEDs workshop, I gave a lightning talk about jQuery vs JavaScript. You can view the slides on speakerdeck, or read a bit more detail here. I’ve also gathered some links on the topic under the tag ctfeds20150822 on my pinboard bookmarks.
I’m not picking on jQuery. I’m just choosing to talk about it because it’s so popular. These things can apply to libraries is general.
The TL;DR is: Think about it. Carefully. What’s the cost (of using jQuery, or the library of your choice)? The one thing I’d like people to do is not to use jQuery by default, but make it a conscious decision.
A good question to ask yourself is: Who does this help? Me or my users?
Good things about jQuery
- It makes complex things simple(r). For example: ajax. That means it can be faster to write than regular JavaScript.
- It’s well maintained and well tested. It has a big team working on it.
- It helps you avoid bugs, even in modern browsers. Although that’s less of an issue these days.
- It’s on a lot of Content Delivery Networks, so the file will be faster to download, or the user may already have it cached in their browser. The various versions of jQuery make this slightly less likely, though.
Bad things about jQuery
- Parse and execution time can be slow. This one is important. Since the file is large, the time it takes a browser to read and execute the jQuery code can be slow, especially on low-powered devices. Older jQuery versions and plugins make this worse.
- It adds a dependency to your set up. Now you (and future you, and other people working on the project) have to know about it and use it.
- It can be overkill if you’re not using all of it, or if it’s something you could write quickly. These days jQuery lets you do modular builds (just pick the bits you need), which is great.
- It can be painful to upgrade. You might need to rewrite sections of your code.
- Like any library, it’s solving a particular set of problems, and these might not be the same as yours.
What are the alternatives?
Some really useful links:
- youmightnotneedjquery.com for regular JavaScript alternatives to jQuery things.
- youmightnotneedjqueryplugins.com for alternatives to jQuery plugin.
- microjs.com for a list of micro-libraries that provide alternatives to jQuery.
And Now for Something Completely Different
Another important thing to think about is Cutting the Mustard: thinking about whether or not you send JavaScript to all your users. The team at BBC news decided to serve all users the basic (fast!) HTML and CSS, but only to send the JavaScript-enhanced, bells and whistles, version to browsers that they could say where “modern enough.” Here’s the test they use:
if('querySelector' in document &&
'localStorage' in window &&
'addEventListener' in window) {
// load fancy js stuff
}
Think about using less JavaScript, and any that you do use: optimise the hell out of it.