Double script tags in Google Analytics tracking code
This is a more curious question than anything else ...
Google suggests adding analytics tracking code as follows:
<script type="text/javascript">
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>
<script type="text/javascript">
try{
var pageTracker = _gat._getTracker("UA-xxxxxx-x");
pageTracker._trackPageview();
} catch(err) {}
</script>
I'm wondering if some JS guru here might tell me why they are splitting it into two script tags rather than sticking it inside. I know that the top can be placed in the header and the bottom just before the body tag to ensure that the page is loaded before it is tracked, but I'm wondering if there is something else for this. Anyone who knew would probably know how to split the code into two tags.
I'm only asking how this comes from Goog and is used by millions of sites ...
thanks
a source to share
It has to be consistent cross-browser, it has to make sure to document.write()
attach the tag it generates before the next script block is executed, so the result looks like this:
<script src='http://www.google-analytics.com/ga.js' type='text/javascript'></script>
<script type="text/javascript">
try{
var pageTracker = _gat._getTracker("UA-xxxxxx-x");
pageTracker._trackPageview();
} catch(err) {}
</script>
If not done in 2 scripts, it _gat
will be undefined in the second script block because it ga.js
hasn't loaded yet ... however, like the script strong> block before, this is the page waiting before executing the code inside the last block, making everything work when it is assumed. Basically the browser is executing script blocks in order , Google uses this fact to load the script when it should be loaded ... which was used before.
a source to share
If I had to guess, I would say it because of the line document.write(unescape(...));
where they dynamically include another JS file. Why are they loading the one I don't know dynamically. I guess it has something to do with whether you are using https or http.
If it was a single file, I doubt the file ga.js
will be loaded in time for the code to run pageTracker
. _gat
does not exist and you will get an error instead of being able to use Google Analytics.
a source to share