JavaScript – head, body or jQuery?

Most recommended method is to put it before </body> tag. Yahoo performance article also suggests that other than YSlow and Page Speed addons by Yahoo and Google respectively.

Quoting from Yahoo article linked above:

The problem caused by scripts is that they block parallel downloads.
The HTTP/1.1 specification suggests that browsers download no more
than two components in parallel per hostname.
If you serve your images
from multiple hostnames, you can get more than two downloads to occur
in parallel. While a script is downloading, however, the browser won’t
start any other downloads, even on different hostnames.

When you put scripts in <head> tag, the browsers goes for them thereby keeping other stuff on hold until scripts are loaded which users will perceive like slow loading of the page. This is why you should put scripts at the bottom.

As for:

$(document).ready(function(){/*Code goes here*/});

It is fired when DOM is available and ready to be manipulated. If you put your code at the end, you won’t necessarily need this but usually this is needed because you want to do something as soon as DOM is available for use.

Leave a Comment