tags:

views:

374

answers:

3

I recently read that for a faster web page load it's a good practice to put the JavaScript links at the end. I did, but now the functions of the referenced file doesn't work. If I put the link at the beginning of the page, everything is fine.

Does this thing of putting JavaScript at the end work only under certain circumstances?

+2  A: 

You do have to pay attention to the ordering, but libraries like JQuery make it easy to do it right. At the end of the page, include all the .JS files you need, and then, either in a separate file or in the page itself, put the Jquery calls to act on the page contents.

Because JQ deals with css-style selectors, it's very easy to avoid any Javascript in the main body of the page - instead you attach them to IDs and classes. This is called Unobtrusive Javascript

Alister Bulman
+1  A: 

Every Yahoo YUI example file I remember has almost all the JavaScript at the end. For example,

It looks like Yahoo Practice is roughly "library code at the beginning of <body>, active code at the end of <body>."

Beware, though, this may result in the Flash of Unstyled Content syndrome.

Thomas L Holaday
+4  A: 

I went through some testing with this as well. If you are loading a Javascript file it is faster to put it at the end BUT it does come with some important caveats.

The first is that doing this often made some of my visual effects noticeable. For example, if I was using jQuery to format a table, the table would come up unformatted and then the code would run to reformat it. I didn't find this to be a good user experience and would rather the page came up complete.

Secondly, putting it at the end made it hard to put code in your pages because often functions didn't exist yet. If you have this in your page:

$(function() {
  // ...
}

Well that won't work until the jQuery object is defined. If it's defined at the end of your page the above will produce an error.

Now you could argue that all that styling code could be put in the external file but that would be a mistake for performance reasons. I started off doing that on a project and then found my page took a second to run through all the Javascript that had been centralized. So I created functions for the relevant behaviour and then called the appropriate ones in each page, reducing the Javascript load run time to 50-200ms.

Lastly, you can (and should) minimize the load time of Javascript by versioning your Javascript files and then using far-futures Expires headers so they're only loaded once (each time they're changed), at which point where they are in the file is largely irrelevant.

So all in all I found putting putting the Javascript files at the end of the file to be cumbersome and ultimately unnecessary.

cletus