-
-
Save acusti/8718758 to your computer and use it in GitHub Desktop.
Barebones google analytics RequireJS module wrapper for “universal analytics” with example of how to use it within a single page application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Google analytics include (using "Universal Analytics") | |
* https://gist.github.com/acusti/8718758 | |
*/ | |
/*global define */ | |
define(function(require) { | |
'use strict'; | |
var ga_amd; | |
// 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(); | |
// Create a function that wraps `window.ga` | |
// This allows dependant modules to use `window.ga` via amd module | |
ga_amd = function () { | |
window.ga.apply(this, arguments); | |
}; | |
// Asynchronously load google's analytics.js; it will take over `window.ga` object after it loads | |
// This allows us to add events to `window.ga` before the library has fully loaded | |
require(['//google-analytics.com/analytics.js']); | |
return ga_amd; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Google analytics tracking | |
*/ | |
/*global define */ | |
define(function(require) { | |
'use strict'; | |
var // Helpers | |
ga = require('app/google-analytics'), | |
// Google analytics settings | |
tracking_id = '{{TrackingID}}', | |
tracking_domain = '{{Domain}}'; | |
return { | |
update : function() { | |
var url = window.location.pathname; | |
// Set up your pageview URL | |
// To push the hash as a path, for example: | |
url += window.location.hash.substr(1); | |
// Track it | |
ga('send', 'pageview', url); | |
}, | |
init : function() { | |
// Initialize analytics | |
ga('create', tracking_id, tracking_domain); | |
ga('send', 'pageview'); | |
} | |
}; | |
}); |
christianhaller
commented
Feb 16, 2015
Does this code work with the current version of Google Analytics? I have been testing the code and ga shows me the amount of users online but it does not show me what screen is being viewed even when I call the update function. Please help
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment