Last active
August 29, 2015 14:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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