A script has no actual use until the HTML has finished loading - a script can’t change the DOM until the HTML has loaded. document.ready
waits for the DOM to load. So, there's no point it holding up important things like stylesheets.
Put the scripts at the bottom of the page (before the </body>
tag) to order to get your HTML and CSS to the user as quick as you can. The browser will be able to render the page much quicker and then scripts can be loaded, rather than leaving a blank page for the user to stare at whilst they wait for scripts to download.
While the browser is progressively rendering the page, if it hits a script tag (i.e. a external Javascript file) everything stops. Scripts have the right of way - while a script is downloading, the browser won’t start any other download. i.e. Images and stylesheets and any other parallel download will be blocked, even on different hostnames.
The disadvantage of putting scripts at the bottom of the page is that because the page will render before scripts have initialised, particularly quick clickers will be able to interact with your site before the Javascript is ready.
Note: The opposite is true for Stylesheets - Stylesheets near the bottom of the page block progressive rendering until all stylesheets have been downloaded and moving them to the document HEAD
eliminates the problem.
There is a neat trick in order to load javascript without making the user wait, you can create a <script/>
element using the DOM createElement()
method and add it to the page just before the closing </body>
tag:
var oScript = document.createElement("script");
oScript.src = "/path/to/my.js";
document.body.appendChild(oScript);
The browser doesn't start downloading the js script until the new <script/>
element is actually added to the page. Once the download is complete, the browser interprets the Javascript code contained within.