Nithin Bekal Posts About

Turbolinks and Google Analytics

27 Nov 2015

Google Analytics tracking code doesn’t play well with Rails apps using Turbolinks. For a long time, we were using Turbolinks compatibilty script, but then I noticed that our bounce rate was suspiciously low.

A bounce rate of under 50% would be considered quite good, but ours was hovering under the 5% mark. On looking at the requests, the script was sending in two pageview requests on each page.

The script was using the old Analytics code, so we decided to switch to the new analytics.js from Google, and make it work with Turbolinks. We’re now using a much simpler method, based on this stackoverflow thread.

First, put this code in the <head> section of your markup:

<%- if Rails.env.production? -%>
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  ga('require', 'linkid');
  ga('create', 'UA-XXXXXXXX-X', 'auto');
<%- else -%>
  function ga() { console.log("Google Analytics"); }
<%- end -%>

This is identical to the default script, except that it is missing the ga('send', ...) line. We’ll put that in a JS file which is part of the asset pipeline.

// app/assets/javascripts/analytics.js
$(document).on('page:change', function() {
  ga('send', 'pageview', window.location.pathname);

NOTE: The above code is for Turbolinks 2.x. As Michael mentions in the comments below, replace page:change with turbolinks:load if you’re using Turbolinks 5.0.

This triggers a pageview request every time Turbolinks loads a page. Switching over to this approach has fixed our problem with incorrect reporting.

Nithin Bekal
Hi, I’m Nithin! This is my blog about programming. Ruby is my programming language of choice and the topic of most of my articles here, but I occasionally also write about Elixir, and sometimes about the books I read. I'm @nithinbekal on Twitter.