在 Require.js 中使用 Google Analytics 的问题 [英] Issue using Google Analytics with Require.js

查看:23
本文介绍了在 Require.js 中使用 Google Analytics 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 require.js (http://requirejs.org/) 用于我的网站到目前为止似乎运行良好.不过,我在尝试包含 Google Analytics 代码时遇到了问题.该代码似乎拒绝添加 utm.gif 并且没有向 Google 发送信标.我想知道这是否是一个范围的事情.

I'm using require.js (http://requirejs.org/) for a number of functions on my site and so far it seems to be working well. I've run into an issue when trying to include Google Analytics code though. The code seems to refuse to add a utm.gif and is not sending off a beacon to Google. I'm wondering if it's a scope thing.

define(function() {
    var Analytics = {};
    Analytics.Apply = function() {
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXX-X']);
    _gaq.push(['_trackPageview']);

    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);
}
return Analytics;
});

ga.debug 不会抛出任何错误并且 utm.gif 不会出现.如果我将代码移到 require.js 之外(我的意思是使用 require.js 的模块化 javascript,因此只需将其内联添加到页面中),utm.gif 将成功添加到页面中,并且 ga.debug 发送其信标.

ga.debug throws no errors and utm.gif does not appear. If I move the code outside require.js (by that I mean the modular javascript using require.js, so just adding it inline to the page), utm.gif is added to the page successfully and ga.debug sends off its beacon.

我发现这个网站似乎成功地使用了它,但我不确定该网站在做什么不同:http://paceyourself.net/2011/05/14/managing-client-side-javascript-with-requirejs/

I found this site that seems to be using it successfully, but I'm not sure what that site is doing different: http://paceyourself.net/2011/05/14/managing-client-side-javascript-with-requirejs/

还有其他人遇到结合 require.js 和 GA 的问题吗?

Anyone else run into issues combining require.js and GA?

推荐答案

其他答案都不适合我,但在阅读了 Google Analytics 文档.

None of the other answers worked for me, but I managed to figure out something that does work, after reading the Google Analytics documentation.

在你的主 app.js

requirejs.config({
    paths: {
        ga: '//www.google-analytics.com/analytics'
    }
});

requirejs(['analytics'], function () {
    ...
});

在它自己的文件 analytics.js 中:

in its own file analytics.js:

define(['ga'], function () {
    window.ga('create', 'UA-XXXXXX-1');
    window.ga('send', 'pageview');
});

这是有效的,因为 requirejs 保证在函数执行时,analytics.js 将完成加载.这意味着 window.ga 函数已准备好接受命令.

This works because requirejs guarantees that by the time the function executes, analytics.js will have finished loading. This means that the window.ga function is ready to accept commands.

这篇关于在 Require.js 中使用 Google Analytics 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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