最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Issue using Google Analytics with Require.js - Stack Overflow

programmeradmin4浏览0评论

I'm using require.js (/) 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/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
}
return Analytics;
});

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.

I found this site that seems to be using it successfully, but I'm not sure what that site is doing different: /

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

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 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.

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/

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

Share Improve this question edited Sep 30, 2011 at 19:29 Yahel 37.3k23 gold badges106 silver badges154 bronze badges asked Jul 25, 2011 at 15:51 booleanboolean 8912 gold badges14 silver badges23 bronze badges 3
  • So it does seem to be a scope issue. When using the code: – boolean Commented Jul 25, 2011 at 21:24
  • (Bah, I really wish enter gave a new line and shift+enter posted, not the other way around...and the comments box ate all my line breaks!) So it does seem to be a scope issue. When using the code: require(["jquery"], function ($) { var foo = require('bar'); }); console.log(foo); I can't get access to 'foo'. I guess as far as javascript goes this makes sense since foo only exists in the scope of require. I suspect though that when ga.js is generated it's looking for _gaq, which can't be found since it's in require. Any thoughts? – boolean Commented Jul 25, 2011 at 21:37
  • Well I'm pretty sure that's impossible to read. – boolean Commented Jul 25, 2011 at 21:53
Add a comment  | 

5 Answers 5

Reset to default 9

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

in your main app.js

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

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

in its own file analytics.js:

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

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.

See this requirejs group thread for a discussion of the issue.

For the latest version of Google Analytics, the code snippet I use with RequireJS is -

<script>
  window.GoogleAnalyticsObject = 'ga';
  window.ga = { q: [['create', 'UA-40327700-1', 'jspm.io'], ['send', 'pageview']], l: Date.now() };
  require(['http://www.google-analytics.com/analytics.js']);
</script>

Here we go:

define([ 'http://www.google-analytics.com/ga.js' ], function ( ga ) {
    ga = { q: [['create', 'UA-18710277-1', 'jspm.io'], ['send', 'pageview']], l: Date.now() };
});

That's the module I am currently using, hat tip to @user2305274

The other solutions didn't work for me when using the newer analytics.js. Putting the URL in directly as a dependency didn't work, because requirejs wasn't able to determine when the script finished loading. The async plugin for requirejs didn't seem to work for me either (although I am using it for the google maps api).

The following approach worked for me:

define(function (require) {

  var module;

  // Setup temporary Google Analytics objects.
  window.GoogleAnalyticsObject = "ga";
  window.ga = function () { (window.ga.q = window.ga.q || []).push(arguments); };
  window.ga.l = 1 * new Date();

  // Immediately add a pageview event to the queue.
  window.ga("create", "{{TrackingID}}", "{{Domain}}");
  window.ga("send", "pageview");

  // Create a function that wraps `window.ga`.
  // This allows dependant modules to use `window.ga` without knowingly
  // programming against a global object.
  module = function () { window.ga.apply(this, arguments); };

  // Asynchronously load Google Analytics, letting it take over our `window.ga`
  // object after it loads. This allows us to add events to `window.ga` even
  // before the library has fully loaded.
  require(["http://www.google-analytics.com/analytics.js"]);

  return module;

});
发布评论

评论列表(0)

  1. 暂无评论