Google Analytics and RequireJS
If, like me, you use AMD-style loading for your JavaScript projects, you might have wondered how to integrate the (non-AMD enabled) Google Analytics library into your project.
Define fallbacks
Many web apps these days are being built with offline capabilities in mind. Go ahead and download http://www.google-analytics.com/analytics.js to your local web folder. We’ll need it as a fallback in a second.
Add the following to your paths config:
paths: {
...
"google-analytics": [
"//www.google-analytics.com/analytics",
"vendor/google-analytics" // this is your local copy
]
}
Shim it!
The GA library doesn’t contain any AMD-detection, so we’ll need to shim it and export the ga global.
shim: {
....
"google-analytics": {
exports: "ga"
}
}
Usage
You’ll need to initialise it. Here’s a basic analytics module I’ve written that serves as an example:
define(["eventbus", "google-analytics"], function (Eventbus, ga) {
var self = {};
self.trackPageView = function (uri) {
// @todo check active ga/connection before each event
ga('send', 'event', 'pageView', uri);
};
self.trackAction = function (type, description) {
ga('send', 'event', type, description);
};
self.trackTiming = function (category, identifier, time) {
time = time || new Date().getTime() - window.performance.timing.domComplete;
ga('send', 'timing', category, identifier, time);
};
Eventbus.on("loading.finished", function () {
ga('create', 'UA-XXXXXXX-X', {
'cookieDomain': 'none'
});
ga('send', 'pageview');
self.trackTiming("webapp", "initialise")
});
return self;
});
You’ll probably want to pass in the tracking code as a config parameter, and check for a valid ga session before each tracked event, or perhaps collect some events when offline and only fire them once back online. Go ahead and be creative!