Skip to content

Instantly share code, notes, and snippets.

@knutwalker
Last active May 11, 2016 02:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knutwalker/8481738 to your computer and use it in GitHub Desktop.
Save knutwalker/8481738 to your computer and use it in GitHub Desktop.
Variation of the Universal Analytics tracking Code (Google Analytics). It can only be safely included once since it overwrites itself. The original script does check against that. Also, document.scripts is not available in Firefox < 9
(function(G,O,o,g,l,e){G.GoogleAnalyticsObject=O;G[O]=function(){G[O].q.push(arguments)},G[O].q=[],G[O].l=+new Date;e=o.createElement('script'),l=o.scripts[0];e.src=g;l.parentNode.insertBefore(e,l)}(this,'ga',document,'//www.google-analytics.com/analytics.js'));
// ===>
ga('create', 'UA-XXXXXXX-Y');
ga('send', 'pageview');
(function(){
// G == this == window
// O == 'ga'
// o == document
// g == '//www.google-analytics.com/analytics.js'
// l == undefined
// e == undefined
// the name of the Analytics object, in case 'ga' clashes with some library
window.GoogleAnalyticsObject = 'ga';
// the Analytics object
window.ga = function() {
// add a task to the Analytics queue
window.ga.q.push(arguments);
};
// the Analytics queue
window.ga.q = [];
// the current timestamp
window.ga.l = +new Date();
// create a new script element; this is assigned to e, which is intentionally left undefined
var script = document.createElement('script');
// scheme-agnostic script url
script.src = '//www.google-analytics.com/analytics.js';
// script.async = true; is implied by every spec-conform browser (Firefox 3.6 makes an exception here)
// insert the script element into the document; this is assigned to l, which is intentionally left undefined
var firstScript = document.scripts[0];
firstScript.parentNode.insertBefore(script, firstScript);
}())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment