Best web-design questions in October 2011

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

18 votes

I am about to embark on a new web project and I plan to put my JS-scripts in the head and before end-body using the following scheme:

  1. Scripts that are essential for the UX of the page goes in the head. As I've picked up perusing the web - scripts in the head is loaded before the page loads, so it would make sense to put scripts that are essential to the user experience there.

  2. Scripts that are non-essential to the design and UX (Google Analytics scripts etc.) of the page goes before the </body>.

Is this a sensible approach?

Another approach would be to put all the scripts in the <head> and add defer attributes to the non-essential scripts - however I've read that older versions of FF doesn't pick up the defer attribute.

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.