Don’t use jQuery to load your scripts if you aren’t using jQuery

March 22nd, 2011

I’ve been noticing a little trend over the last couple of months. Developers using jQuery to run a script that doesn’t actually have any jQuery in it, they just want to use the $(document).ready() to run the script when the page is loaded. Here’s an example of what I mean:

1
2
3
4
5
$(document).ready(function() {
 var canvas = $('#canvas')[0],
       ctx = canvas.getContext('2d');
 ctx.fillRect(10,10,100,100);
});

That will draw a black square on a canvas with the id of canvas and everything works just fine. So what’s my problem with it? There is nothing there that requires jQuery for it to work. In fact, because I’m using jQuery to load it and select the canvas, I’m actually running a lot more code than I need to. Don’t forget that every time you use jQuery, you have to load jQuery first, which is 29Kb even after it’s been minified. 29Kb isn’t that much, which is why jQuery is a great framework to work with but for something like in my example, it’s 29Kb that I don’t need to load. Not only do I have to load it first, after it’s loaded I need to run the jQuery code in order to select the canvas element on the page. So, now, for three lines of JavaScript, I’ve loaded and run a 29Kb JS file that I didn’t need to.

So what would I do in this circumstance? Well, JavaScript gives us a couple of options. If I’m just testing and getting things to work, then there’s not reason not to just put the code in the head tag and use window.onload to run our script.

1
2
3
4
5
6
function draw() {
 var canvas = document.getElementById(‘canvas’),
       ctx = canvas.getContext(‘2d’);
 ctx.fillRect(10,10,100,100);
}
window.onload = draw;

That does the exact same thing as the example that uses jQuery and will run a lot faster and use a lot less resources. In fact, correct me if I’m wrong, but I’m pretty sure using document.getElementById is actually faster than using $(‘#canvas’) and I’ve seen a few examples where the developer is using jQuery but uses the getElementById method to select the elements on the DOM.

Another example would be to put the script at the bottom of the HTML document and change one line:

1
2
3
4
5
6
function draw() {
 var canvas = document.getElementById(‘canvas’),
       ctx = canvas.getContext(‘2d’);
 ctx.fillRect(10,10,100,100);
}
draw();

In this example, the draw function will run just fine because the canvas has been loaded in the document by the time the browser gets to the script. (It’s a best practice to put your scripts, both in page and external, at the end of the document)

I’m not hating on jQuery, I use it all the time. But don’t just default to using it when you can build things that run faster and use less resources with plain old JavaScript. It’ll speed up your sites and make you a better programmer in the long run.

Leave a Reply

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