Google Tag Manager and Turbolinks in Ruby on Rails

I’m pretty new to Ruby on Rails (and coding in general), but I finally got my first little app up and running and so naturally I wanted to add Google Tag Manager to it so I could track traffic to it.

Turns out that the Turbolinks gem doesn’t play well with GTM. I googled around for it and everyone was pointing to this article, which I was going to try as a last resort because I’m just not a fan of virtual pageviews and it just seems like their should be a way to get Turbolinks to fire JS when you tell it to.

I read the Turbolinks docs and found this:

Running JavaScript When a Page Loads

You may be used to installing JavaScript behavior in response to the window.onload, DOMContentLoaded, or jQuery ready events. With Turbolinks, these events will fire only in response to the initial page load—not after any subsequent page changes.

In many cases, you can simply adjust your code to listen for the `turbolinks:load` event, which fires once on the initial page load and again after every Turbolinks visit.

javascriptdocument.addEventListener("turbolinks:load", function() {// ...})

I used that snippet to modify my GTM `<script>` tag so it looks like this:

<script> document.addEventListener("turbolinks:load", function() {
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= ''+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-XXXXXXX');
console.log("GTM fired"); }) </script>

I put in the `console.log(“GTM fired”);` so I could see in the console when it was firing. When I debugged it, it fired once and only once on each page load and my events are firing correctly too.

Like I said, I’m new to Rails, so YMMV. Leave a comment if works or I’m breaking something without realizing it.