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