tags:

views:

74

answers:

2

For speed purposes, I'm trying to decide whether to place my JavaScript in the <head> or just before the </body> of my site. I prefer the head and am not concerned with the extra HTTP request, just the behavior of this script.

Here are the two code snippets, which are loaded back-to-back (Google Analytics):

Script 1:

// Loaded externally:
// <script type="text/javascript" src="google_analytics_1.js"></script>

var gaJsHost = (
    ( "https:" == document.location.protocol ) ?
    "https://ssl." :
    "http://www."
);

document.write( unescape(
    "%3Cscript src='" +
    gaJsHost +
    "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"
) );

Script 2:

// Loaded externally:
// <script type="text/javascript" src="google_analytics_2.js"></script>

try {
    var pageTracker = _gat._getTracker( "UA-0000000-0" );
    pageTracker._trackPageview();
}
catch( err ) { }

With the code above, does JavaScript delay sending the rest of the page until it retrieves ga.js, or does it instead say, "okay, I've got the request for ga.js queued up, now I will continue to send the rest of the page while we wait for it to download to the client..."?

My instinct tells me it is linear, and that the page will be delayed until ga.js has been completely downloaded by the client. Is that right?

A: 

Nop. It won't be delayed. It will queue up the first request and continue with the second one, actually it's the browser that handle's it.

hminaya
Wow, really!? I'm a little surprised to hear that. =)
Jeff
A: 

The parsing of the page will pause while loading the ga.js file, but the server will continue sending the rest of the page. When the script has been loaded and executed, it will continue with the rest of the page.

So, the script and the rest of the page will load in parallel, but it won't touch any of the rest of the page until the script has been processed.

Guffa
Okay, lol. That's basically the exact opposite of the answer from hminaya. Right?
Jeff
@Jeff: That depenends, his response is a bit unclear, so depending on whether he is referring to the download or the parsing, it can be interpreted either way. The parsing is most definitely delayed, but not the download.
Guffa
Thanks Guffa. So just to be clear, in order to achieve my goal of having the page load faster, I should put the script just above `</body>` instead of in the head. Right?
Jeff
Yes, by putting the scripts last in the page, your page will load and display before requesting the external scripts. In an ideal world you would want all the scripts in the head, but to make your page less sensetive to problems that other servers may have, you have to go with what works. I moved some external scripts down the page myself a while ago, as our page was having problems because the scripts took too long to load.
Guffa