Skip to content

Instantly share code, notes, and snippets.

@sivicencio
Last active August 29, 2015 14:19
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 sivicencio/4e8465a7eca1c9a39604 to your computer and use it in GitHub Desktop.
Save sivicencio/4e8465a7eca1c9a39604 to your computer and use it in GitHub Desktop.
JavaScript implementation of @reed Google Analytics Turbolinks compatibility. Original CoffeeScript version: http://reed.github.io/turbolinks-compatibility/google_analytics.html
// JavaScript implementation of @reed Google Analytics Turbolinks compatibility
// Original CoffeeScript version: http://reed.github.io/turbolinks-compatibility/google_analytics.html
// Prefer Universal Analytics if you can, as Google recommends
var googleAnalytics = {
load: function() {
var firstScript;
window._gaq = [];
window._gaq.push(["_setAccount", googleAnalytics.analyticsId()]);
ga = document.createElement("script");
ga.type = "text/javascript";
ga.async = true;
ga.src = (document.location.protocol === "https:" ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";
firstScript = document.getElementsByTagName("script")[0];
firstScript.parentNode.insertBefore(ga, firstScript);
if(typeof(Turbolinks) !== undefined && Turbolinks.supported) {
document.addEventListener("page:change", function() {
googleAnalytics.trackPageview();
}, true)
}
else {
googleAnalytics.trackPageview();
}
},
trackPageview: function(url) {
if ( !googleAnalytics.isLocalRequest() ) {
if (url) {
window._gaq.push(["_trackPageview", url]);
}
else {
window._gaq.push(["_trackPageview"]);
}
window._gaq.push(["_trackPageLoadTime"]);
}
},
isLocalRequest: function() {
return googleAnalytics.documentDomainIncludes("local");
},
documentDomainIncludes: function(str) {
return document.domain.indexOf(str) !== -1;
},
analyticsId: function() {
// Replace the following string with your own tracking code
return "tracking_code";
}
};
googleAnalytics.load();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment