JavaScript in <head> or just before </body>?
I think a lot of developers run JavaScript just before the </body>
so that it is run 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 run 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.
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.
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).
JavaScript code 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 JavaScript code 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 Google's CDN too.
See Best Practices for Speeding Up Your Web Site for more information.
One of the reasons you'd want to put scripts before the </body>
is if they manipulate the DOM without user interaction, so you'll need the DOM to be loaded in order to be manipulated. Another way to do that is to add an event listener and run the scripts when the page has loaded, but this will require additional code, which might get complicated if you have a lot of scripts, especially ones you haven't written yourself. Putting them at the end of the page also will speed up page load, though in the case of DOM manipulating scripts you might get some not-so-pretty results from that.