Whenever you put a script
element in a page, regardless of where it is, unless you use the defer
or async
attributes and the browser your visitor is using supports them, all HTML parsing comes to a full stop and control is given over to the JavaScript interpreter (waiting for the script file to download, if the script is in a separate file). This holds up the rendering of your page. So unless you have a really good reason for putting the script tag somewhere else, putting the script tag at the very bottom of your page will improve its apparent loadtime.
There can be really good reasons, of course. For instance, if the script has to use document.write
to output HTML to the page (like many ad scripts do), then of course it has to be in the location where that HTML has to go. Similarly, if you have a button in your UI and you're hooking up a handler to that button that calls your script, if the script is further down in the page, there may be a window of opportunity for the user to click the button before your script is there to handle the click, either doing nothing or getting an error, either of which negatively affects the user experience.
If your page is fully functional without any script (good practice for most general-purpose websites), with the script merely enhancing the experience, put the script at the bottom. If the script is critical to the functionality of your site (perfectly acceptable practice for some sites, and certainly for many web-based applications), best to have your build process combine all of your custom JavaScript into one file, minify it, and link it in the head
, so that you're holding things up as briefly as possible. (If your script relies on libraries, you can load them separately from a CDN for speed, or prepend them to your custom code, depending on your assessment of which will be faster for your users.)
That's all a speed/perceived speed argument. From a separation of concerns standpoint, make sure all of your JavaScript is in separate files (at least, separate source files; you could have a build process that mergers your JavaScript into your HTML to produce an ouput file to serve to the user without violating separation of concerns; but then you can't get caching of your JavaScript if you use it on more than one page). Once you have a separate JavaScript file, you're going to have to link to the script somewhere, I don't think it really makes a big difference from a separation of concerns standpoint where as long as you don't have script elements littered all over the HTML source.
Edit: See also David Murdoch's answer quoting Google on the value of inline script blocks for hooking up UI. I wanted to reference it but couldn't find it; he did. It's a pain because (unless you do this with a build script) it really messes up separation of concerns. On the up side, it shouldn't be that hard to do with tags and a build script...