Put JavaScript includes at the bottom of your page

I was reading the jQuery Cookbook yesterday to try and sharpen my JavaScript skills.  Within the first chapter the book highlights something which I’ve never given much attention to – where in your page to include your JavaScript files.  Here is an excerpt.

… modern optimization techniques have declared that pages load faster when the JavaScript is loaded by the browser at the end of a page parse. In other words, if you put JavaScript code at the bottom of a web page, then the browser will load everything in front of it before it loads the JavaScript. This is a good thing because most browsers will typically stop processing other loading initiatives until the JavaScript engine has compiled the JavaScript contained in a web page. It’s sort of a bottleneck in a sense that you have JavaScript at the top of a web page document.

So it’s basically a performance enhancement – your pages will load quicker due to your JavaScript includes being at the bottom of your page (just before the closing <body> element).

There’s another reason why it’s a good idea to do your JavaScript includes at the bottom of your page.  I usually attach all my event handlers and initial function execution inside a ready() function, for example:

$(document).ready(function() {
    alert("Go for it the DOM is loaded");

If we simply do all JavaScript includes at the bottom of the page this is no longer necessary – the DOM will be loaded by the time our JavaScript is executed.  This means we can do away with the ready() function – less code is better.  Small beans perhaps, but every little bit helps.

I realize that for some situations it’s easier to place JavaScript in the <head> element, but I can’t really think of a scenario where this is absolutely required.  I actually think the ASP.NET MVC team should think about changing the default project templates to do the JavaScript includes at the bottom of the page, rather than in the <head> element.

Happy coding.