3

得到 _gaq is undefined error in IE7 和 IE8

我的脚本如下

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXX']);
    _gaq.push(['_setDomainName', 'yyy.com']);
    _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>

我可以为 _gaq 分配默认值吗? 参考这个链接

4

1 回答 1

7

Based on your reply to my comment, the answer to this question is

Google Analytics moved to a new, more modern way of handling events several years ago, allowing browsers to load a complete page without having to wait for a response from the GA servers. Whereas in the past, you were guided to put the <script> snippet provided by google near the end of the page (just before the closing body tag), now you should instead include the tag somewhere in the <head> section of your HTML.

The new script works by defining a javascript variable _gaq as an array, that is treated like a queue. Pageviews, events and other stuff you want to track is pushed onto the array, which is effectively instant. When there is time, the GA code will check the array for contents and pop them off, processing the requests to the GA server until the array is empty.

A side effect of the _gaq variable is that the script tag must be in the HTML before it is referenced, or else you'll get the JS error _gaq is undefined.

For example as documented here in the Google Analytics event tracking guide you might want to know when a user plays a video on your site like this:

<a href="#" onClick="_gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']);">Play</a>

Notice the reference to the variable _gaq here. If not defined already, you'll get the error.

Short answer: put the async javascript snippet in the <head> of your HTML.

于 2012-11-16T20:38:21.717 回答