If the script tag is above or below the body in a HTML page, does it matter for the performance of a website?
And what if used in between like this:
Javascript assets, by default, tend to block any other parallel downloads from occurring. So, you can imagine if you have plenty of <script>
tags in the head, calling on multiple external scripts will block the HTML
from loading, thus greeting the user with a blank white screen, because no other content on your page will load until the JS files have completely loaded.
In order to combat this issue, many developers have opted to placing JS at the bottom of the HTML page (before the </body>
tag). This seems logical because, most of the time JS is not required until the user begins interacting with the site. Placing JS files at the bottom also enables progressive rendering.
Alternatively, you can choose to load Javascript files asynchronously. There are plenty of existing methods which this can be accomplished by:
XHR Eval
var xhrObj = getXHRObject();
xhrObj.onreadystatechange =
function() {
if ( xhrObj.readyState != 4 ) return;
eval(xhrObj.responseText);
};
xhrObj.open('GET', 'A.js', true);
xhrObj.send('');
Script DOM Element
var se = document.createElement('script');
se.src = 'http://anydomain.com/A.js';
document.getElementsByTagName('head')
[0].appendChild(se);
Meebo Iframed JS
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
doc.open().write('<body onload="insertJS()">');
doc.close();
To name a few...
Note: Only a maximum of five scripts can be loaded in parallel in current browsers.
ForIE
there is the defer attribute you can use like so:
<script defer src="jsasset.js" type="text/javascript"></script>
When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering.
Yes, it does affect the performance of the web page.
The problem with JavaScript is that is blocks the execution/loading of the rest of the page. If you have something that takes a long time in your JavaScript then it will prevent the rest of the page from loading:
See these examples:
You can see the effect the alert has on the rendering of the rest of the page. Any JavaScript that you put into the top of your page will have the same effect. In general, it is better to put anything critical to the layout of your page (i.e. menu plugins or something). Anything that requires a user interaction (popup handlers) or doesn't involve the user at all (Google Analytics) should go to the bottom of the page.
You can get lazy loaders that will inject your script
tags into your code. Since the code isn't on the HTML, you can be sure that your whole page has rendered correctly and that the JS you're including will not block anything.