Created
October 18, 2014 18:23
-
-
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.
This file contains hidden or 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
# 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