Thread: JS fundamentals
View Single Post
Old 09-25-2012, 06:15 PM   PM User | #40
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by zygezund View Post
Why to keep scripts in the <body>, not in the <head>?
Traditionally everyone placed script tags in the head, because the body was for content and the head was for everything else. It was just "how it was done".

Actually the script tag is the only thing that can appear in the head and can also appear in the body, everything else (meta, link, style, title, and so on elements) should stay in the head.

So the best reason for moving script tags out of the head and placed just before the closing body tag is this:

"A <script src="url"></script> will block the downloading of other page components until the script has been fetched, compiled, and executed. It is better to call for the script as late as possible, so that the loading of images and other components will not be delayed. This can improve the perceived and actual page loading time. So it is usually best to make all <script src="url"></script> the last features before the </body>. An in-page <script> does not have a significant impact on loading time."
From the guru himself Douglas Crockford: http://javascript.crockford.com/script.html

So if you're using a lot of JavaScript in external files; for example using a big library with plugins and so on, you will probably improve you page load times by following Crockford's advice.

If you have the script in the head, it downloads the script before the rest of the page, and so the microsecond that the page has loaded, it can start executing the script. If you have the script at the end of the body, it will load the page first, the page will appear quicker on your screen, and then it will download and execute the script, which leads to a longer gap between the page appearing and the script running.

But to be candid I don't think it is an issue worth arguing about. It will rarely make any perceptible difference to the user in most situations.
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Last edited by Philip M; 09-25-2012 at 06:18 PM..
Philip M is offline   Reply With Quote
Users who have thanked Philip M for this post:
zygezund (09-26-2012)