Skip to content

Instantly share code, notes, and snippets.

@stephen-puiszis
Created October 18, 2014 18:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephen-puiszis/f01c65294333d93e0c68 to your computer and use it in GitHub Desktop.
Save stephen-puiszis/f01c65294333d93e0c68 to your computer and use it in GitHub Desktop.
Turbolinks / Google Analytics Integration using new analytics.js library. Uses Gon to pass Rails settings variables to the coffescript.
# google_analytics.js.coffee
class @GoogleAnalytics
@load: ->
window['GoogleAnalyticsObject'] = 'ga'
window['ga'] = window['ga'] || ->
(window['ga'].q = window['ga'].q || []).push arguments
window['ga'].l = 1 * new Date()
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
#Creates Google Analytics and additional dependencies
#For testing locally, switch 'auto' with {'cookieDomain': 'none'}
ga('create', GoogleAnalytics.analyticsId(), 'auto')
ga('require', 'linkid', 'linkid.js')
ga('require', 'displayfeatures')
# Check if Turbolinks is supported
if typeof Turbolinks isnt 'undefined' and Turbolinks.supported
document.addEventListener "page:change", (->
options =
page: document.location.pathname
title: document.title
location: document.URL
GoogleAnalytics.trackPageview(options)
), true
else
GoogleAnalytics.trackPageview()
return true
@trackPageview: (options = {}) ->
ga('send', 'pageview', options)
@analyticsId: ->
gon.google_analytics_id
GoogleAnalytics.load()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment