Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimal location for javascript includes

I've read that it is better to place your <script> tags at the end of the document. The argument for doing this appears to be that the browser will stall rendering the page below a script tag until it has loaded and and executed the script. If your script tag is at the top of the page, rendering is stalled for a while, which is bad.

However, I am not sure if this is really true any more.

Looking around, I normally see the following locations...

In the <head> of the page or Just inside the <body> tag

Stackoverflow is an example of a site that puts the script tags in the head, and since they are normally rather obsessed with performance, I am starting to wonder if position in the page is important at all.

Last thing in the body element

The other common place to put javascript appears to be right at the very end of the <body> element. I am assuming this means that the page can render while the javascript downloads and gets on with doing its thing.

But which is better?

Does anyone have any thoughts or advice on this? I am looking to try and get our pages to perform and appear to the user as quickly as possible.

Does it matter? What are the advantages of being at the top of the page? Bottom of the page?

like image 895
Rik Heywood Avatar asked Nov 19 '25 09:11

Rik Heywood


1 Answers

It really depends.

There is no catch all answer for this because it depends on what your javascripts are acting on.

Putting scripts at the end of the page is sometimes needed if your acting on a DOM element that needs to be loaded for the script to run. Say you want to focus on a control and your script is:

var mytext = document.getElementById("mytext2"); 
mytext.focus();

Well in this case you would want it to execute at the end of the page, after mytext2 control has already been loaded by the browser. This is less important for script blocks that only contain functions that are called by events.

If you have a big .js file that contains libraries of functions you may also want to put that at the end of the page so the browser will load the page faster before loading the large .js file.

Google analytics suggests putting their tracker at the end, to make sure the page has been delivered before you count the hits, but in some cases it suggests putting the script into the header too, it works both ways.

So, rule of thumb for me is, HEAD scripts for everything except things that execute in-line and act on DOM objects, or large scripts that you want to load after the page.

Rick Strahl just wrote a great blog on placement of Javascript in .net too:

like image 197
Tj Kellie Avatar answered Nov 21 '25 22:11

Tj Kellie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!