Google Analytics gtag with Rails 5 and Turbolinks
Get your Ruby on Rails 5 application working with Turbolinks and the new gtag.js for Google Analytics
Google has rolled out a new way to send your data to Google Analytics, Adwords and more called gtag.js. This seems to be the new default when adding new properties to Google Analytics. The old guides for how to integrate Turbolinks with Google Analytics no longer work with the new gtag.js.
Turbolinks will speed up your Ruby on Rails (and other) applications by intercepting any page changes(clicking on links) and instead loading them with AJAX and replacing the body. This means that the browser doesn’t have to parse all the assets again like Javascript and CSS. If you have a lot of Javascript this can give you a huge performance boost.
In order to get Google Analytics working with Turbolinks however you have to hook into this AJAX load in order to send the page change to Google Analytics. In the past you used the ga
function to do that but that doesn’t work with the gtag.js API.
What you do instead is put this at the very top of the head
-part of your application
layout file:
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_TRACKING_ID');
document.addEventListener('turbolinks:load', event => {
if (typeof gtag === 'function') {
gtag('config', 'GA_TRACKING_ID', {
'page_location': event.data.url
});
}
});
</script>
Replace the GA_TRACKING_ID
with your Google Analytics tracking id.
The interesting part is in the turbolinks:load
part which uses the new gtag api to send page locations when Turbolinks loads a new page.
Now it works just fine!