Best place to write javascript code in HTML document

Javascript is an indispenseable language in a web developer arsenal. It has also evolved, from simple scripting to a more complex language, thanks to AJAX and JQuery. As with new technology evolution, the way to do things are also different. Today, I am going to cover, where is the best place to write Javascript code confined in <script> tag inside a HTML document ?

My personal preference is to store the javascript functions into an external javascipt library and call the library in the <head> tag. While the call to the functions inside the library are made inline.

However, the standard storage location, as suggested by Yahoo Exceptional Performance team is to put them at the end of the HTML, just before the </body> tag. Why ? There are two reasons for this :

  1. The page is able to load, all element are rendered, before the javascript is called.
  2. All DOM inside the HTML document are rendered, meaning, the javascript can safely call any element inside the HTML document.

There is a disadvantage also to that method. It is possible that the user interacts with the HTML DOM elements before the javascript has a chance to load properly, therefore bypassing the javascript completely. A disaster if field checking for database insertion relies on javascript method alone.

For a good debate on the placement at the top or at the bottom, check out the discussion over at Stack Overflow “Where is the best place to put <script> tags in HTML markup?“. The arguments there are valid and backed by reference materials.

A good tutorial for placement and understanding how javascript works is found in Javascript Tutorial “Adding a script to HTML“. It showcases all methods with their respective advantage and disadvantage.

In summary, based on my experience and preference, there is no “fixed” way to place javascript code inside HTML document. It all depends on the script function and the needs for the particular page.

Thanks to Guta for sharing the links and making me think about this particular topic.