Skip to content

Instantly share code, notes, and snippets.

@ches
Last active December 20, 2015 21:08
Show Gist options
  • Select an option

  • Save ches/6194954 to your computer and use it in GitHub Desktop.

Select an option

Save ches/6194954 to your computer and use it in GitHub Desktop.
analytics.js load routine annotated
// Create a queue, but don't obliterate an existing one!
var analytics = analytics || [];
(function () {
// A list of all the methods we want to generate queueing stubs for.
var methods = [
'identify', 'track', 'trackLink', 'trackForm', 'trackClick', 'trackSubmit',
'page', 'pageview', 'ab', 'alias', 'ready', 'group'
];
// For each of our methods, generate a queueing method that pushes arrays of
// arguments onto our `analytics` queue. The first element of the array
// is always the name of the analytics.js method itself (eg. `track`), so that
// we know where to replay them when analytics.js finally loads.
var factory = function (method) {
return function () {
analytics.push([method].concat(Array.prototype.slice.call(arguments, 0)));
};
};
for (var i = 0; i < methods.length; i++) {
analytics[methods[i]] = factory(methods[i]);
}
}());
// Define a method that will asynchronously load analytics.js from our CDN.
analytics.load = function(apiKey) {
// Create an async script element for analytics.js based on your API key.
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = ('https:' === document.location.protocol ? 'https://' : 'http://') +
'd2dq2ahtl5zl1z.cloudfront.net/analytics.js/v1/' + apiKey + '/analytics.min.js';
// Find the first script element on the page and insert our script next to it.
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
};
// Load analytics.js with your API key, which will automatically load all of the
// analytics integrations you've turned on for your account. Boosh!
analytics.load('REDACTED');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment