How to add Google Analytics tracking that works with Turbolinks

Turbolinks is a really nice way to improve your Rails 4 application's speed. It uses AJAX to load the pages and just replace the body element of your page. The official Google Analytics tracking code does not play nice with this approach, but we can easily make it work.

The following code snippet is a nice and clean solution for a couple of reasons:

  • It works nicely with Turbolinks
  • Degrades to work even without Turbolinks enabled
  • Uses the new tracking code
  • You can use it to track page views manually by invoking GoogleAnalytics.trackPageview()

The only thing that you need to do, is add this code snippet to your main javascript file and load this file in your websites head. Don't forget to change the TRACKING-ID with yours.

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 = '//'

        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

    @trackPageview: (url) ->
        unless GoogleAnalytics.isLocalRequest()
            if url
                ga 'send', 'pageview', url
                ga 'send', 'pageview'

    @isLocalRequest: ->
        document.domain.indexOf('dev') isnt -1

    @analyticsId: ->


Fork the gist to meet your needs.

comments powered by Disqus