Double script tags in Google Analytics tracking code
This is more a curiosity question than anything else...
Google instructs to add the 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 some JS guru here could tell me why they're separating it into two script tags instead of sticking it all inside one. I know that the top part could be put in the header and the bottom part just before body tag to 开发者_如何转开发ensure the page loaded before it's tracked, but I'm wondering if there's something more to it. Anyone who'd know that would likely know how to separate the code into two tags anyway.
I'm only asking as this is coming from the Goog and is being used by millions of sites...
Thanks
This is to be consistent cross-browser, it needs to make sure that document.write()
sticks the tag it's generating in before the next script block runs, 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 it didn't do it in 2 scripts, _gat
would be undefined in the second script block because the ga.js
hasn't loaded yet...however as a script block before that one, the page waits before executing the code inside the last block, making it all work when it's supposed to. Basically, the browser executes script blocks in order, google's taking advantage of this fact to load the script when it needs to be loaded...which is before it's used.
If I had to guess, I would say it's because of the document.write(unescape(...));
line where they're dynamically including another JS file. Why they're loading that one dynamically I don't know. I'd guess that has to do with whether or not you're running https or http.
If it was one file, I doubt the ga.js
file would be loaded in time to run the pageTracker
code. _gat
wouldn't exist, and you'd get an error rather than being able to actually use Analytics.
精彩评论