Issue using Google Analytics with Require.js

若如初见. 提交于 2019-12-03 00:23:27

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;

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!