javascript - 加载谷歌分析参数化异步页面跟踪脚本

标签 javascript google-analytics

如果我使用谷歌分析 async site tracking script ,在我页面的 head 部分的末尾,一切都按预期工作:

<head>   
    <script type="text/javascript">

        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-XXXXX-X']);
        _gaq.push(['_setDomainName', 'test.com']);
        _gaq.push(['_trackPageview', '/title=ied&action=fire']);

        (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>
</head>

在fiddler中可以看到2个请求:

enter image description here enter image description here

出于某种原因,我需要对脚本进行参数化,所以我将其包装在自定义 googleAnalytics 函数中,该函数获取 2 个参数:

function googleAnalytics(domain, queryString) {
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXX-X']);
    _gaq.push(['_setDomainName', domain]);
    _gaq.push(['_trackPageview', queryString]);

    (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);
    })();
}

Abowe 代码已保存到 GoogleAnalytics.js 文件中。我将它加载到 head 部分的页面,如下所示:

<head>
    <script src="/script/GoogleAnalytics.js" type="text/javascript" language="javascript"></script>
    <script type="text/javascript">googleAnalytics('test.com', '/title=ied&action=fire');</script>
</head>

但是这次fiddler只显示了1个请求:

enter image description here

Google Analytics Tracking Code Debugger也没有显示。 仅下载 ga.js 脚本,但没有其他请求为谷歌分析报告填充数据。这种方法有什么问题,如何解决?

顺便说一句:我需要这 2 个参数和跟踪脚本的异步版本。

问候

最佳答案

您的问题是您的 _gaq 声明在范围内是局部的。 ga.js 加载,并在全局范围内查找 _gaq。 (一旦脚本被注入(inject),它就无法再访问函数的范围。)

要修复它,您可以放置​​ var _gaq = _gaq || []; 在函数外,或者你可以在函数内用这个替换它:

window._gaq = window._gaq || []; 

这将解决您的问题。

关于javascript - 加载谷歌分析参数化异步页面跟踪脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6582062/

相关文章:

php - 通过 Google_Service_AnalyticsReporting_Report 获取下一个报告页面

google-analytics - 使用谷歌分析跟踪直接文件下载

javascript - 如何在 NodeJS/ExpressJS/Passport 中显示登录的用户名?

javascript - jQuery:还有另一种解决方案吗?

javascript - Electron:如何与浏览器窗口通信?

Javascript, Chrome

ajax - 如何在 Google Analytics 中将 session 标记为非弹跳

javascript - AMCHARTS xy 图表数据标签

google-analytics - 通过测量协议(protocol)为经典电子商务发送多项目交易

regex - 使用POSIX正则表达式提取查询参数值