Charlie & Co.

_gat is undefined: New Analytics Code

So Google has updated their analytics engine and added some new code for users to put on their sites.  That’s great, right?  It’s good to see a company releasing updates to a free product.  Not entirely.

It would seem that their new code doesn’t work 100% of the time and it leaves out about 75% of the hits and tracking for your site.

_gat is undefined

This is the error that shows up in Firebug, IE7′s error console and Safari.

This is happening because the script (ga.js) doesn’t have enough time to load before you try to feed it the tracking ID (UA-XXXX-XX) into it.

What’s the solution?

The solution is very simple.  Delay the code.

So change the code from this :

<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">
var pageTracker = _gat._getTracker("UA-XXXXXX-X");
pageTracker._trackPageview();
</script>

to this :

<script src="http://www.google-analytics.com/ga.js" type="text/javascript"></script>
<script type="text/javascript">
var pageTracker;
setTimeout('startGA();', 500);
function startGA()
{
pageTracker = _gat._getTracker("UA-XXXXXX-X");
pageTracker._initData();
pageTracker._trackPageview();
}
</script>

So how does this fix your problem?  We create a new function called startGA (Start Google Analytics) and as you can see we have set a timeout of 500ms or 1/2 second. This gives the script enough time to run before you try to feed it variables and use it.

You should also never use the document.write function. The W3C compatibility rules pretty much said it was the anti-christ of code.

If you have any questions about the proper implimentation of the google analytics code.  Please do not hesitate to ask us.