如何扩展谷歌分析以跟踪 AJAX 等(根据 H5BP 文档) [英] How to extend google analytics to track AJAX etc (as per H5BP docs)

查看:20
本文介绍了如何扩展谷歌分析以跟踪 AJAX 等(根据 H5BP 文档)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试安装 H5BP 的 extend.md 文件(https://github.com/h5bp/html5-boilerplate/blob/v4.3.0/doc/extend.md)

它指出优化的"谷歌分析 JS 代码段包括以下代码:

var _gaq = [['_setAccount', 'UA-XXXXX-X'], ['_trackPageview']];

并且应该在_gaq之后添加额外的增强,例如track jquery AJAX requeststrack javascript errorstrack page scroll 已定义.

实际上,当前版本的 H5BP 中包含的代码段并未将 _gaq 作为变量引用:

 (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;e=o.createElement(i);r=o.getElementsByTagName(i)[0];e.src='//www.google-analytics.com/analytics.js';r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));ga('create','UA-XXXXX-X');ga('send','pageview');

当尝试使用任何 H5BP 扩展时,这会产生一个未定义的错误.例如.

if (typeof _gaq !== "undefined" && _gaq !== null) {$(document).ajaxSend(function(event, xhr, settings){_gaq.push(['_trackPageview', settings.url]);});}

不会工作,因为 _gaq 未定义.

这些增强功能打算如何实施?有人可以提供一个工作示例,显示所有扩展的完整实现吗?

谢谢

您尝试添加的代码不起作用,因为 _gaq 是一个用于将跟踪信标推送到旧版本的数组谷歌分析 (GA) 版本.但是 HTML5 BoilerPlate (H5BP),在您似乎正在使用的最新版本中,已经更新自身以使用 Universal Analytics (UA),Google 发布的下一个 GA 版本.这可以从协议相对 URL //www.google-analytics.com/analytics.js 以及最新版本的文档中看到.不幸的是,您提到的文档尚未更新,因为 H5BP 上给出的链接为来源优化的 GA 代码,本身已更新为 UA 的代码,并且是 H5BP 源现在使用的.

因此,您扩展 _gaq 对象使用的附加源代码将不起作用,因为您没有使用具有处理推送数据的功能的 ga.js到 GA 的 _gaq 对象,但是 UA 的 analytics.js,它不初始化任何这样的对象,如 _gaq 或具有处理功能推送到_gaq的数据.

但是,在升级自己以使用 analytics.js (UA) 之前,H5BP 有一个 GA 版本的脚本,就像这样(我得到了这个,由曾经使用过 H5BP 的朋友提供):

<!-- Google Analytics:将 UA-XXXXX-X 更改为您网站的 ID.--><脚本>var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];//这里_gaq被初始化(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'));

理想情况下,这应该替换您提到的代码行,即

(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;e=o.createElement(i);r=o.getElementsByTagName(i)[0];e.src='//www.google-analytics.com/analytics.js';r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));ga('create','UA-XXXXX-X');ga('send','pageview');

如果你这样做了,那么你对代码的使用

if (typeof _gaq !== "undefined" && _gaq !== null) {$(document).ajaxSend(function(event, xhr, settings){_gaq.push(['_trackPageview', settings.url]);});}

等等,使用 _gaq 会起作用.

另请记住,您当前使用的 H5BP 代码是最好的,因为 Google 正在逐步淘汰 GA,以使 Universal Analytics 成为分析的未来.我提到的旧代码不再有效(或将在不久的将来停止工作,具体取决于 Google).在UA升级中心阅读更多相关信息.

请记住,当前的 H5BP 使用 UA (analytics.js) 代码,这是谷歌提供的优化形式,如发现 此处.

这就解释了为什么 extend.md 中提到的脚本在您似乎正在处理的 H5BP 上不起作用,这是通过实现旧代码的一种可能的解决方法.您需要的是一种使用现有脚本跟踪 AJAX 等的方法.为此,每次 AJAX 请求完成时,您只需记录一次虚拟浏览量.您可以找到类似的场景 此处.在那里提问者将跟踪应用于模态的打开.您可以应用相同的技术来跟踪页面或部分页面的 AJAX 调用和检索.我在答案中指定的 VURL 在您的情况下可以是 /virtual/ajax/url-of-page-retrieved-via-ajax.>

如果您不想发送虚拟浏览量,您还可以为每个 AJAX 请求发送自定义事件.在此处详细了解 UA 中的事件跟踪.

如果你想知道你指定的函数的参数代表什么,你可以阅读此处.这是您提到的 extend.md 文件中的脚本的位置.修改脚本以用于 UA 的尝试可能如下所示:

(函数 ($) {//将所有 jQuery AJAX 请求记录到 Google Analytics$(document).ajaxSend(function(event, xhr, settings){ga('send','pageview',settings.url.pathname);});})(jQuery);

ajaxSend() 方法是一个回调,每次 jQuery AJAX 调用完成时都会触发它.记住这里的 jQuery 这个词.这仅适用于 jQuery AJAX 请求.xhr 一般代表 XMLHttpRequest.我认为它假设人们知道 jQuery AJAX 调用是什么,我对此不是很了解.

要使用 UA 跟踪 Javascript 错误,类似的脚本是:

(函数(窗口){变量未定义,链接 = 函数 (href) {var a = window.document.createElement('a');a.href = href;返回一个;};window.onerror = 函数(消息、文件、行、列){var 主机 = 链接(文件).主机名;ga('发送','事件',(host == window.location.hostname || host == undefined || host == '' ? '' : 'external') + 'error',消息,文件 + ' LINE: ' + line + (column ? ' COLUMN: ' + column : ''),{'非交互':1});};}(窗户));

同样收集:Event Category 将是 host+error,Action 将是错误消息,label 将指向错误发生的位置(行号、文件名等).

跟踪页面滚动也很相似:

$(function(){var isDuplicateScrollEvent,scrollTimeStart = 新日期,$window = $(window),$document = $(document),滚动百分比;$window.scroll(function() {scrollPercent = Math.round(100 * ($window.height() + $window.scrollTop())/$document.height());if (scrollPercent > 90 && !isDuplicateScrollEvent) {//页面滚动到 90%//如果你想跟踪页面滚动的其他滚动百分比,你//可以编辑数字 90,或者编写额外的条件 ga('send',...) 调用//在这个块内并相应地改变标签,指定百分比//滚动.isDuplicateScrollEvent = 1;ga('发送','事件','滚动','窗口:' + $window.height() + 'px;文档:' + $document.height() + 'px;时间:' + Math.round((new Date - scrollTimeStart )/1000,1) + 's',{'非交互':1});}});});

在这里,事件类别将是 scroll,动作将是窗口、高度和文档以及时间.如果您想将滚动跟踪为交互式事件(这意味着如果您希望用户在滚动时被跟踪为非反弹用户),您可以删除行 {'nonInteraction':1}

希望有帮助!:)

I am trying to install the google analytics augments identified in the extend.md file of H5BP (https://github.com/h5bp/html5-boilerplate/blob/v4.3.0/doc/extend.md)

It states that the "optimised" google analytics JS snippet includes the following code:

var _gaq = [['_setAccount', 'UA-XXXXX-X'], ['_trackPageview']];

and that additional augments such as track jquery AJAX requests, track javascript errors and track page scroll should be added after _gaq is defined.

In fact, the snippet included with the current version of H5BP does not make reference to _gaq as a variable:

        (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
        function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
        e=o.createElement(i);r=o.getElementsByTagName(i)[0];
        e.src='//www.google-analytics.com/analytics.js';
        r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
        ga('create','UA-XXXXX-X');ga('send','pageview');

This creates an undefined error when trying to use any of the H5BP extensions. E.g.

if (typeof _gaq !== "undefined" && _gaq !== null) {
    $(document).ajaxSend(function(event, xhr, settings){
        _gaq.push(['_trackPageview', settings.url]);
    });
}

Will not work as _gaq is not defined.

How are these augments intended to be implemented? Can someone provide a working example showing a full implementation of all the extensions?

Thanks

解决方案

The code you are trying to add will not work, as _gaq was an array used to push the tracking beacons to in the older Google Analytics (GA) version. But the HTML5 BoilerPlate (H5BP), in its latest version you seem to be using, has updated itself to make use of Universal Analytics (UA), the next version of GA which Google has released. This can be seen from the protocol-relative URL //www.google-analytics.com/analytics.js and also the docs for the latest version. Unfortunately, it seems the doc you mentioned hasn't been updated, as the link given at the H5BP for the source of the optimised GA code, has itself been updated with code for UA and that is what the H5BP source is now using.

Consequently, your additional source code extending the use of the _gaq object will not work, as you are not using ga.js which has functions to process the data pushed to the _gaq object from GA, but the analytics.js for UA, which does not initialise any such object as _gaq or have functions to process the data pushed to _gaq.

But, before upgrading itself to use analytics.js (UA), H5BP had a GA version of the script, like this (I got this, courtesy of a friend who used to work with H5BP):

<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
    <script>
        var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']]; //here the _gaq was initialised
        (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
        g.src='//www.google-analytics.com/ga.js';
        s.parentNode.insertBefore(g,s)}(document,'script'));
    </script>

Ideally, this should replace the lines of code you mentioned, namely

(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
    function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
    e=o.createElement(i);r=o.getElementsByTagName(i)[0];
    e.src='//www.google-analytics.com/analytics.js';
    r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
    ga('create','UA-XXXXX-X');ga('send','pageview');

If you did that, then your use of the code

if (typeof _gaq !== "undefined" && _gaq !== null) {
$(document).ajaxSend(function(event, xhr, settings){
    _gaq.push(['_trackPageview', settings.url]);
});
}

and so on which use _gaq will work.

Also remember that the H5BP code you are currently using is best, as Google is phasing out GA in a move to make Universal Analytics the future of analytics. The older code I have mentioned no longer works (or will stop working in the near future, depending on Google). Read more about this at UA Upgrade Center.

Keep in mind that the current H5BP uses UA (analytics.js) code which is an optimised form of what Google provides, as found here.

That explains why the scripts mentioned in extend.md won't work on the H5BP you seem to be working on, an a possible workaround by implementing the old code. What you need is a way to track AJAX etc. with the script you do have in place. For that, each time an AJAX request completes, you can simply record a virtual pageview. You can find a similar scenario here. There the asker applies the tracking to the opening of a modal. You can apply the same technique to track AJAX calls and retreives of a page or partial page. The VURL as I've specified in the answer can be, in your case, /virtual/ajax/url-of-page-retrieved-via-ajax.

If you do not wish to send virtual pageviews, you can also send customised events for each AJAX request. Read more about event tracking in UA here.

If you want to know what the arguments of the function you specified stand for, you can read here. This is where the script in the extend.md file you mentioned was taken. An attempt to modify the script for use with UA would probably look like this:

(function ($) {
  // Log all jQuery AJAX requests to Google Analytics
  $(document).ajaxSend(function(event, xhr, settings){ 
    ga('send','pageview',settings.url.pathname);
  });
})(jQuery);

The ajaxSend() method is a callback which is fired every time a jQuery AJAX call is completed. Remember the word jQuery here. This only works for jQuery AJAX requests. xhr generally stands for XMLHttpRequest. I think it assumes one knows what a jQuery AJAX call is, I'm not very knowledgeable about that.

To track Javascript errors using UA, a similar script would be:

(function(window){
var undefined,
    link = function (href) {
        var a = window.document.createElement('a');
        a.href = href;
        return a;
    };
window.onerror = function (message, file, line, column) {
    var host = link(file).hostname;
    ga('send','event',
        (host == window.location.hostname || host == undefined || host == '' ? '' : 'external ') + 'error',
        message, file + ' LINE: ' + line + (column ? ' COLUMN: ' + column : ''),
        {'nonInteraction': 1});
    };
}(window));

This collects likewise: Event Category will be host+error, Action will be the error message, and label will point to where the error occurred (line no, filename, etc.).

Tracking page scroll is also very similar:

$(function(){
var isDuplicateScrollEvent,
    scrollTimeStart = new Date,
    $window = $(window),
    $document = $(document),
    scrollPercent;

$window.scroll(function() {
        scrollPercent = Math.round(100 * ($window.height() + $window.scrollTop())/$document.height());
        if (scrollPercent > 90 && !isDuplicateScrollEvent) { //page scrolled to 90%
//If you want to track for page scroll for some other percentage of scroll, you
//can edit the number 90, or write additional conditional ga('send',...) calls
//inside this block and vary the label accordingly, specifying the percentage
//of scroll.
            isDuplicateScrollEvent = 1;
            ga('send','event','scroll',
            'Window: ' + $window.height() + 'px; Document: ' + $document.height() + 'px; Time: ' + Math.round((new Date - scrollTimeStart )/1000,1) + 's',
            {'nonInteraction':1}
        );
        }
    });
});

Here, Event Category will be scroll, Action will be thw Window, height and document, and time. If you want to track scroll as an interactive event (which means if you want a user to be tracked as a non-bounce user if he scrolls) you can remove the line {'nonInteraction':1}

Hope that helps! :)

这篇关于如何扩展谷歌分析以跟踪 AJAX 等(根据 H5BP 文档)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆