Skip to content

Instantly share code, notes, and snippets.

@jonwolfe
Created December 10, 2013 20:22
Show Gist options
  • Save jonwolfe/7897610 to your computer and use it in GitHub Desktop.
Save jonwolfe/7897610 to your computer and use it in GitHub Desktop.
This is how we use Google Analytics with Turbolinks. I put this in a analytics.js.coffee file and require it after turbolinks. That's it. Works on browsers that support Turbolinks and those that don't. Also works with parts of your app that may not use Turbolinks. If you need to record pageviews manually for any reason, just call GoogleAnalytics…
class @GoogleAnalytics
@load: ->
# Google Analytics depends on a global _gaq array. window is the global scope.
window._gaq = []
window._gaq.push ["_setAccount", GoogleAnalytics.analyticsId()]
# Create a script element and insert it in the DOM
ga = document.createElement("script")
ga.type = "text/javascript"
ga.async = true
ga.src = ((if "https:" is document.location.protocol then "https://ssl" else "http://www")) + ".google-analytics.com/ga.js"
firstScript = document.getElementsByTagName("script")[0]
firstScript.parentNode.insertBefore ga, firstScript
# If Turbolinks is supported, set up a callback to track pageviews on page:change.
# If it isn't supported, just track the pageview now.
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
window._gaq.push ["_trackPageview", url]
else
window._gaq.push ["_trackPageview"]
window._gaq.push ["_trackPageLoadTime"]
@isLocalRequest: ->
GoogleAnalytics.documentDomainIncludes "local"
@documentDomainIncludes: (str) ->
document.domain.indexOf(str) isnt -1
@analyticsId: ->
# your google analytics ID(s) here...
GoogleAnalytics.load()
@jonwolfe
Copy link
Author

The description at the top is hard to read, so here it is again:

This is how we use Google Analytics with Turbolinks. I put this in a analytics.js.coffee file and require it after turbolinks. That's it.

Works on browsers that support Turbolinks and those that don't. Also works with parts of your app that may not use Turbolinks.

If you need to record pageviews manually for any reason, just call GoogleAnalytics.trackPageview(url).

This snippet also does not track pageviews on local requests (change isLocalRequest() to match part of your local hostname).

Also supports multiple google analytics account IDs via the analyticsID() method. This is useful if you have a site that runs on multiple domains. Just documentDomainIncludes() to decide which analytics ID to return.

@carlosramireziii
Copy link

What changes would be required in order to support Universal Analytics tracking codes?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment