'Does the <script> tag position in HTML affects performance of the webpage?

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.



Solution 1:[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:

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.

Update 2022: all browsers now accept the defer attribute.

Solution 2:[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:[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:[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:

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:[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.

Solution 6:[6]

Firstly script tags not inside body/head elements create invalid HTML and might even cause some exceptions in some browsers.

Script tags inside the head element will be loaded and interpreted before any HTML is rendered, this blocks HTML/CSS rendering.

Script tags at the bottom of the body tag, will not block HTML/CSS and since you can only play around with the DOM on DomReady, this is the best position to put your JavaScript. As a side note, you won't even need to use a domReady event wrapper.

Alternatively, you can also use libraries like LABJS and RequireJS to kickstart your JavaScript from the head tag (minimal HTML/CSS blocking). Any scripts loaded through either of these libraries will run in paralel to HTML/CSS rendering.

<head>
   <script data-main="INITSCRIPT.js" src="require.js"></script>
</head>

INITSCRIPT.js

require( [ "jQuery" , "somePlugin" ] , function(){
   $(document).ready(function(){
      $("#someId").somePlugin();   
   });
} );

In the above example, only the load and interpretation of require.js will block HTML/CSS rendering, which usually is insignificant. After which jQuery and somePlugin will be loaded in paralel, so HTML/CSS renders just nicely.

Solution 7:[7]

Performance of the script itself will definitely be the same.

The placement is important though, as explained in the article you linked, since the browser will "halt" (or "freeze") simultaneous downloads and rendering of the page when it encounters and loads the contents of a <script> tag. So it's probably best to let the browser render the page and apply CSS styles, and then include your .js. It will look smoother to the user.

Also, including the script at the bottom probably means right before you close the <body> tag.

Solution 8:[8]

Along with the Performance aspect, you also need to be careful whenever you include the <script> tag inside the <head> tag.

Let's consider the following example:

<head>
 <script>document.getElementById("demo").innerHTML="hello";</script>
</head>
<body>
 <p id="demo">The content of the document......</p>
</body>

Here, notice that the script is loaded before the DOM (or the <p> tag) is loaded, which causes a failure in the script (Since the getElementById cant find the element with name 'demo').

In such cases you have to use the script within the body tag only.

Considering the other answers, its better to have the script always before the </body> tag as you never know whether the scripts that you would load externally have any such dependencies on your DOM.

Reference: Detailed problem description

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zaffer
Solution 2 reectrix
Solution 3
Solution 4 Jonathon Bolster
Solution 5 Wolph
Solution 6 BGerrissen
Solution 7 Ian
Solution 8 Community