So how do we decide which of those two places to put the script tag? There are a few things we need to consider and the one that has the biggest impact is whether our web page is using HTML or is using XHTML. Note that which of these two you are using depends on the MIME type of the page with text/html being the MIME type for HTML and application/xml-xhtml being the MIME type for XHTML. Using an XHTML doctype with an HTML MIME type still means your page is HTML and so you should consider it as HTML for the following discussion.
The XHTML DOM works differently. Nothing in the XHTML DOM can be accessed until the DOM finishes loading. You therefore need to test for the DOM having loaded as the minimum requirement for being able to access anything in the page regardless of where you place the script tag.
Older browsers do not provide a way to test specifically if the DOM has loaded and so for those browsers you need to wait until the entire page has finished loading or alternatively set up a loop to test for when the appropriate element becomes accessible before accessing it if you place your script in the head of your page or are using XHTML.See faster DOM access for one way to set this up.
Another consideration for script placement is the way that web browsers load web pages. With all file types except for scripts old browsers could load files two at a time. For newer browsers the number of files they can load simultaneously has been increased to eight provided that none of them is a script. It is only in the very latest browsers where there is even a slight possibility that a script referenced from within your web page will be able to load at the same time as any other files referenced from the page.The script will wait until all the files currently loading finish lading and will force all the other files that have yet to start loading to wait until the script finishes loading.
What this means is that if you place your script tag closer to the end of your page then you allow all the other files your page needs to load first and so the page will appear to load much faster. This provides another good reason for placing your script at the end of the body rather than in the head.
While placing your scripts in the head of the page may look neater because it reserves the body for what will actually appear in the web page, placing the script there will slow the loading of your page (which you can only minimise by reducing that script to one which dynamically adds the script tags after the page last loaded) and where the script itself will need to be more complex so as to ensure that the code doesn't try to run before the appropriate parts of the DOM are available.