So, as I said earlier, I have started using Google Analytics. Google now suggests some new code to use in running the analytics. The problem: it’s broken! Here’s their code:
<script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? " https://ssl." : "http://www."); document.write("\<script src='" + gaJsHost + " google-analytics.com/ga.js' type='text/javascript'>\<\/script>" );
var pageTracker = _gat._getTracker("UA-xxxxxx-x"); pageTracker._initData(); pageTracker._trackPageview(); </script>
Now for what is broken:
- There is a space between the " and google-analytics.com. This causes browsers to load the wrong (and invalid) address
- Code that is dependent on code in the ga.js is executed immediately after the html is written to load the external javascript. There is no explicit indication as to the order this should be done. Race condition!
So, here is the fixed code:
<script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? " https://ssl." : "http://www.");
document.write("\<script src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'>\<\/script>" ); document.write("\<script type='text/javascript'>var pageTracker = _gat._getTracker(\"UA-2245403-1\");" + "pageTracker._initData();" + "pageTracker._trackPageview();" + "\<\/script>"); </script>
The space is removed, and the executed code is now explicitly after the loading of the external script. Nice and sloppy code you’ve got there Google.