Problem using Google Analytics with Require.js

advertisements

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?


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.