Last active
March 20, 2016 23:08
-
-
Save mupkoo/6732ee2ddb6bbaf92466 to your computer and use it in GitHub Desktop.
Google Analytics snippet for Turbolinks
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
class @GoogleAnalytics | |
@load: -> | |
# Load the analytics code | |
window['GoogleAnalyticsObject'] = 'ga' | |
window['ga'] = window['ga'] || -> | |
(window['ga'].q = window['ga'].q || []).push arguments | |
window['ga'].l = 1 * new Date() | |
# Add the script | |
googleScript = document.createElement("script") | |
googleScript.async = 1 | |
googleScript.src = '//www.google-analytics.com/analytics.js' | |
firstScript = document.getElementsByTagName("script")[0] | |
firstScript.parentNode.insertBefore googleScript, firstScript | |
# Create the analytics | |
ga 'create', GoogleAnalytics.analyticsId(), 'auto' | |
# You can enable additional modules like so | |
# ga 'require', 'displayfeatures' | |
if typeof Turbolinks isnt 'undefined' and Turbolinks.supported | |
document.addEventListener "page:change", GoogleAnalytics.trackPageview, true | |
else | |
GoogleAnalytics.trackPageview() | |
@trackPageview: (url) -> | |
unless GoogleAnalytics.isLocalRequest() | |
if url | |
ga 'send', 'pageview', url | |
else | |
ga 'send', 'pageview' | |
@isLocalRequest: -> | |
document.domain.indexOf('dev') isnt -1 | |
@analyticsId: -> | |
'TRACKING-ID' | |
GoogleAnalytics.load() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment