A common problem with Google Analytics is the “_gat is not defined” javascript error, when you try to load a webpage that uses Google Analytics to track visitors behavior.
This happens because the visitor most likely has an AdBlocker installed (such as AdBlock Plus for Firefox), which filters out a javascript file from Google. The code then tries to create an instance of an object it doesn’t know (because the definitions are missing, since the file isn’t included) and it throws the “_gat is not defined” error.
We wouldn’t be showing the problem, if there weren’t a solution of course. Just change your code to the following, which will check if the object actually exists before trying to create an instance of that object. The tracker won’t fully work (but it didn’t in the first place anyway), but at least the user won’t be shown the nasty javascript error.
<script type="text/javascript">
if (typeof(_gat) == 'object') {
var pageTracker = _gat._getTracker("UA-CODE");
pageTracker._trackPageview();
}
</script>
This only happens if you try to use the New Tracking Code (ga.js) (the new, and “improved” version) over the old Legacy Tracking Code (urchin.js). The bug’s been around for a while, it’s strange Google hasn’t provided a clear fix for this yet …
Update: new Analytics code doesn’t have this problem anymore. If you edit your Site-details in Google Analytics, and view your Google Analytics code, you’ll see something similar to 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">
try {
var pageTracker = _gat._getTracker("UA-MYCODE");
pageTracker._trackPageview();
} catch(err) {}</script>
Error handling has prevented the error message to be shown. It is advised to use the code that Google provides, instead of the “hack” shown on top of this page.