Skip to content

Instantly share code, notes, and snippets.

@yields
Forked from gingerlime/analytics_js_loader.js.erb
Last active December 31, 2015 12:09
Show Gist options
  • Save yields/7984105 to your computer and use it in GitHub Desktop.
Save yields/7984105 to your computer and use it in GitHub Desktop.
// sources: https://segment.io/libraries/analytics.js#getting-started
// https://github.com/phillbaker/analytics-js-rails/blob/master/app/views/analytics-js/_loader.html.erb
// Create a queue, but don't obliterate an existing one!
window.analytics || (window.analytics = []);
// A list of all the methods in analytics.js that we want to stub.
window.analytics.methods = ['identify', 'track', 'trackLink', 'trackForm',
'trackClick', 'trackSubmit', 'page', 'pageview', 'ab', 'alias', 'ready',
'group', 'on', 'once', 'off'];
// Define a factory to create queue stubs. These are placeholders for the
// "real" methods in analytics.js so that you never have to wait for the library
// to load asynchronously to actually track things. The `method` is always the
// first argument, so we know which method to replay the call into.
window.analytics.factory = function (method) {
return function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(method);
// see https://github.com/segmentio/analytics.js/issues/253#issuecomment-24280169
if(!window.analytics.push){
window.analytics.push = Array.prototype.push.bind(window.analytics);
}
window.analytics.push(args);
return window.analytics;
};
};
// For each of our methods, generate a queueing method.
for (var i = 0; i < window.analytics.methods.length; i++) {
var method = window.analytics.methods[i];
window.analytics[method] = window.analytics.factory(method);
}
// Define a method that will asynchronously load analytics.js from our CDN.
window.analytics.load = function (callback) {
// 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 = '<%= asset_path("analytics.min.js") %>';
script.addEventListener('load', function (e) {
if(typeof callback == 'function') {
callback(e);
}
}, false);
// 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);
};
// Add a version so we can keep track of what's out there in the wild.
window.analytics.SNIPPET_VERSION = '2.0.6';
window.analytics.load(function() {
window.analytics.initialize({
'Google Analytics' : {classic: true,
siteSpeedSampleRate: 100,
trackingId: '<%= config.analytics_account %>'},
'Mixpanel': {token: '<%= config.mixpanel_account %>',
people: true},
'trak.io': '<%= config.trakio_account %>'
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment