Skip to content

Instantly share code, notes, and snippets.

@EvanWillms
Last active August 29, 2015 14:03
Show Gist options
  • Save EvanWillms/6e0d725d4eb1bd43a4a4 to your computer and use it in GitHub Desktop.
Save EvanWillms/6e0d725d4eb1bd43a4a4 to your computer and use it in GitHub Desktop.
segmentio/analytics.js open source script load
// Create a queue, but don't obliterate an existing one!
window.analytics = window.analytics || [];
// A list of the methods in Analytics.js to stub.
window.analytics.methods = ['identify', 'group', 'track',
'page', 'pageview', 'alias', 'ready', 'on', 'once', 'off',
'trackLink', 'trackForm', 'trackClick', 'trackSubmit'];
// Define a factory to create stubs. These are placeholders
// for methods in Analytics.js so that you never have to wait
// for it to load to actually record data. The `method` is
// stored as the first argument, so we can replay the data.
window.analytics.factory = function(method){
return function(){
var args = Array.prototype.slice.call(arguments);
args.unshift(method);
window.analytics.push(args);
return window.analytics;
};
};
// For each of our methods, generate a queueing stub.
for (var i = 0; i < window.analytics.methods.length; i++) {
var key = window.analytics.methods[i];
window.analytics[key] = window.analytics.factory(key);
}
// Define a method to load Analytics.js
// and that will be sure to only ever load it once.
analytics.load = function(callback) {
if (document.getElementById('analytics-js')) return;
// We make a copy if our dummy object
window.a = window.analytics
// Create an async script element
var script = document.createElement('script');
script.type = 'text/javascript';
script.id = 'analytics-js';
script.async = true;
//script.src = '/media/js/analytics.js';
script.src = 'https://raw.githubusercontent.com/segmentio/analytics.js/master/analytics.js'
script.addEventListener('load', function(e) {
if (typeof callback === 'function') {
callback(e);
}
}, false);
// Insert our script next to the first script element.
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(script, first);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment