Search code examples
javascriptscriptingheaderfooter

Should javascript code always be loaded in the head of an html document?


Is there a blanket rule in terms of how javascript should be loaded. I'm seeing people saying that it should go on the end of the page now.

Thoughts?


Solution

  • Well there are two cases (at least) depending on what do you want to achieve. If you need the functionality incorporated in the script or scripts, like function libraries, available before or during page loading then you should load JavaScript code in the head tag. If you need to do something that needs some resources that are made available only after the page is loaded (DOM resources that is) than you should load the script/s at the bottom of the page (this can also be solved using onDOMReady events that are already available in most of the JavaScript frameworks). There could be also some performance issues that could dictate your decision. For instance there are situations when loading the script or scripts in the head tag would slow down the page rendering and if you can provide basic functionality with page rendered until the script are fully functional then again the script or scripts should be loaded at the bottom. It is more or less a decision based on what you need to do.