Problem using Google Analytics with Require.js


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']);

    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '';
    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?

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

    paths: {
        ga: '//'

requirejs(['analytics'], function () {

in its own file analytics.js:

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

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