Uncaught ReferenceError: _gaq is not defined (Google Analytics)

Alex Brown picture Alex Brown · May 1, 2012 · Viewed 54.8k times · Source

The following message appears when viewing a site page in the chrome debug log.

Uncaught ReferenceError: _gaq is not defined

The page itself is supposed to track an object using the onload event handler and fire a _trackEvent for Google Analytics.

My best guess is that perhaps the ga.js file doesn't load in time and therefore the onload _trackEvent triggered is not caught. the async snippet is being used before the </body> close and the object is positioned in the middle <body>.

(some other posts have referenced jQuery position too but, this might be a red herring)

any assistance greatly appreciated.

Answer

PJ Brunet picture PJ Brunet · Mar 10, 2014

From https://developers.google.com/analytics/devguides/collection/gajs/ this code replaces your existing "traditional snippet" with the "latest, asynchronous version, you should remove the existing tracking snippet first."

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

To see your events come in (to know if this is working) look for "Events" under the "Real-Time" menu option on the left side of the "Reporting" page.