Where to Put JavaScript (and How to Get Faster Page Loads)
Where is the correct location for JavaScript in the source code of a web page?
You see it everywhere — in the HEAD area, within the content of the BODY area, at the end of the BODY area, above the HTML tag, and below everything else on the page.
The correct place for JavaScript may seem to be without rhyme or reason. But there is.
There are logical explanations and reasons.
The Location On the Page for JavaScript
In general, JavaScript can be put anywhere into the source code of a web page so long as it's in the HEAD or BODY area. Not that it won't run if put into other areas, but it should be put where the browser expects to find it.
Exceptions
The exception is when areas of the web page need the JavaScript while the web page is loading. In that case, the JavaScript must be located somewhere before (above) the place where it will be used.
Although it might not strictly be called "JavaScript," this needs to be mentioned: JavaScript can be specified in HTML tag attributes; attributes like onclick, onmouseover, and onfocus. Such JavaScript needs to remain where it is, as the value of the attribute.
There you have it, the logical explanations and reasons why.
But there's more to it, another thing to consider.
Page Load Speed
(In this section, "page load speed" means the time it takes for the content to be available in the browser for the site visitor.)
The lower in the source code JavaScript is located at, the faster the page loads. Especially when the JavaScript is obtained from an external file or URL, as it takes extra time to fetch the file. (This isn't a treatise on SEO, but my understanding is that search engines like faster loading pages.)
Generally, JavaScript is loaded and parsed when it's encountered.
To accomplish the fastest page load, put the JavaScript near the end of the BODY area — unless it needs to be available to the web page content during page load. In that case, it may be possible to put that earlier-needed JavaScript into the HEAD area and the rest at the end of the BODY area.
Here are a few examples of JavaScript needs to be available during page load:
-
Timers to start when the page begins loading.
-
JavaScript to focus the mouse cursor in a certain form field.
-
A div to be revealed or hidden with JavaScript depending on whether or not a certain cookie is set.
Virtually all JavaScript not needed during page load can be located at or near the bottom of the BODY area.
Recap
When JavaScript is required at any point in the source code while the page is loading, put the JavaScript somewhere above that point.
All other JavaScript can go anywhere in the HEAD or BODY area, the lower on the page the faster the main content of the page will load.
(This article first appeared in Possibilities ezine.)
Will Bontrager