Skip to content

Instantly share code, notes, and snippets.

@bruab
Created March 14, 2016 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bruab/6f65124241ad133e7a0f to your computer and use it in GitHub Desktop.
Save bruab/6f65124241ad133e7a0f to your computer and use it in GitHub Desktop.
Boilerplate code for Google Analytics integration
/* _optimizely_evaluate=force */
$(window).load(function() {
var experimentID = TODO_PASTE_IN_HERE; // ex: 9876543210
try { // wait till window.load so ga exists via segment.io
var cookieName = 'ga_optimizely_' + experimentID;
if (!getCookie(cookieName)) {
setCookie(cookieName, 'sent', 30 * 60); // resend every 30m
window.ga('send', {
hitType: 'event',
eventCategory: 'optimizely',
eventAction: window.optimizely.data.experiments[experimentID].name,
eventLabel: window.optimizely.variationNamesMap[experimentID],
nonInteraction: true
});
}
} catch (e) {}
/*jshint latedef:false*/
function setCookie(name, value, optSeconds) {
'use strict';
var expires = '';
if (optSeconds) {
var date = new Date();
date.setTime(date.getTime() + (optSeconds * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
function getCookie(name) {
'use strict';
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
});
/* _optimizely_evaluate=safe */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment