Does the <script> tag position in HTML affects performance of the webpage?
Solution 1
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:
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.
Update 2022: all browsers now accept the defer
attribute.
Solution 2
So I know this is an old discussion, but I've been reading about this topic and reading other answers on StackOverflow...
It actually doesn't matter where you put the jQuery tag anymore:
Finally, a word about persistent folklore. You may have encountered the frequently repeated advice to “always place JavaScript at the bottom of the page just before the closing tag”. This was once true because web browsers loaded scripts sequentially and blocked loading and rendering until each script was complete. This is no longer true; modern browsers do “preload scanning” and begin loading all scripts in parallel, whether listed in the head element or at the bottom of the page. External JavaScript often is loaded asynchronously and is written so it won’t execute until the page is loaded and the DOM is ready. Loading a script in the head element is no longer a bad practice.
http://railsapps.github.io/rails-javascript-include-external.html
Solution 3
Script elements at the top of the document are available sooner (so you can bind event handlers and have JS run as soon as an element becomes available), but they do block parsing of the rest of the page.
Script elements at the bottom aren't (so you can't) and there isn't any significant page left, so it doesn't matter if that is blocked.
Which is best depends on the relative importance priority (which has to be determined on a case-by-case basis) of having the JS running Vs. having the HTML rendering.
Note that a script element at the bottom must appear inside the body element. So it should be:
<script>...</script></body></html>
and not
</body><script>...</script></html>
Solution 4
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:
- Script at top, blocks whole page: http://jsfiddle.net/jonathon/wcQqn/
- Script in the middle, blocks bottom: http://jsfiddle.net/jonathon/wcQqn/1
- Script at bottom, blocks nothing: http://jsfiddle.net/jonathon/wcQqn/3/
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.
Solution 5
Yes, it does affect the performance of the webpage loading.
The problem is, normal <script>
tags are blocking so everything after the script tag has to wait till the script tag is done loading and parsing before the rest of the page can load.
Now someone will probably note that if you use async="true"
in your script tag, it won't block. But that's only supported by a couple of browsers yet so that won't help the general case yet.
Either way, in general it's a good idea to place your script tags at the bottom of the page so they won't hold up other parts of the page.
Pratik
Updated on May 30, 2020Comments
-
Pratik almost 4 years
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:
<body> ..blah..blah.. <script language="JavaScript" src="JS_File_100_KiloBytes"> function f1() { .. some logic reqd. for manipulating contents in a webpage } </script> ... some text here too ... </body>
Or is this better?:
<script language="JavaScript" src="JS_File_100_KiloBytes"> function f1() { .. some logic reqd. for manipulating contents in a webpage } </script> <body> ..blah..blah.. ..call above functions on some events like onclick,onfocus,etc.. </body>
Or this one?:
<body> ..blah..blah.. ..call above functions on some events like onclick,onfocus,etc.. <script language="JavaScript" src="JS_File_100_KiloBytes"> function f1() { .. some logic reqd. for manipulating contents in a webpage } </script> </body>
Need not tell everything is again in the
<html>
tag!!How does it affect performance of webpage while loading? Does it really? Which one is the best, either out of these 3 or some other which you know?
And one more thing, I googled a bit on this, from which I went here: Best Practices for Speeding Up Your Web Site and it suggests put scripts at the bottom, but traditionally many people put it in
<head>
tag which is above the<body>
tag. I know it's NOT a rule but many prefer it that way. If you don't believe it, just view source of this page! And tell me what's the better style for best performance. -
Pratik over 13 yearsWhat if two js files come from different paths or servers even can they load simultaneously ?
-
Russell Dias over 13 years@Rahul Joshi Of course. High traffic sites usually tend to invest in a Content Delivery Network, which is a cookieless domain intended for static content. So, yes two js files can come from different servers, although the load time will depend on the server in question.
-
Pratik over 13 yearsBut it can be simultaneous,thus reducing overall time ?
-
Russell Dias over 13 years@Rahul Joshi Sorry, Yes they can. Not really reducing overall time, the bulk of the content is just presented to the user much quicker. In reality it is just perceived to be loaded quicker.
-
whostolemyhat over 13 yearsThe position of the script doesn't affect the speed of the page loading - this is reliant on your internet connection. It actually affects the perceived performance - the visible elements of the page load first (rather than having to wait for a script to load), so the page appears to load faster than usual, while actually taking the same amount of time.
-
Wolph over 13 years@What: not completely true unfortunately, since it blocks your browser from loading other files while loading the script tag it results in the page loading slower. While it is loading the page won't be able to load the images while those could normally be loaded in parallel during the entire pageload.
-
Jacob over 12 yearsThis looks like a fascinating read, but your image is yielding a 404. Do you have a replacement image URL?
-
Daniel Wood about 9 yearsIn Safari 8 each of those examples is exactly the same and the alert blocks everything.
-
Daniel Sokolowski over 8 yearsBefore having to worry about
<script>
tag placement you'll have many other lower hanging performance fruits to pick so code for maintainability, ease of development, and readability. -
dagnelies over 7 yearsAccording to browser network tools, this answer appears to be plain wrong and scripts are loaded in parallel and do not block other resources. It just delays the rendering/execution of the body.
-
kidkkr about 5 yearsThis code example shows how modern browser works which above answer describes.
-
Matthieu over 4 yearsBecause it's an old discussion, your answer makes more sense now. And it's now old too ;)