JavaScript in <head> or just before </body>? JavaScript in <head> or just before </body>? javascript javascript

JavaScript in <head> or just before </body>?


I think a lot of developers run javascript just before the </body> so that it is ran after all the elements have been rendered.

However, if you organise your code correctly, the position on the page doesn't matter.

For example, when using jQuery, you can ensure the code isn't ran until the page and its elements are fully rendered by doing the following:

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

Then the script reference can be put in the head tag.


Update - Script tags should be referenced just before </body>. This prevents render blocking while the scripts load and is much better for site perception speed.

No obtrusive javascript should be used when using this technique.


Javascript should be placed at the end of the document so that it doesn't delay the parallel loading of page elements. This does then require that the js is written in a specific way but it does improve the speed of page loads.

Also, ideally you could host references like this under a different (sub)domain. References to jquery should be pointed to googles CDN too.

See http://developer.yahoo.com/performance/rules.html for more info.


I'd say that's perfectly sensible. As you said, as long as you don't move essential scripts (e.g. jQuery, Modernizr, etc etc) out from the <head>, you shouldn't have problems.

Moving non-essential scripts to the bottom of the page should help with the perceived loading speed (that and minimizing / concatenating scripts).