Turbolinks and Google Analytics
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:
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.
The above code is for Turbolinks 2.x.
As Michael mentions in the comments below,
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.