Turbolinks
Turbolinks makes navigating your site faster by intercepting link clicks and loading pages via AJAX instead of full page reloads. This requires a slightly different setup than usual, as Turbolinks handles page transitions differently from most.
Why Turbolinks needs manual tracking
When a visitor clicks a link in a Turbolinks app, Turbolinks intercepts it, fetches the new page via AJAX, swaps the current page body with the new content, and updates the address bar URL. This means standard "document ready" events never fire because the page isn't actually reloading.
Fathom's data-spa="auto" setting listens for pushState and popState events, but Turbolinks fires these at different times than typical SPA routers. This causes pageviews to be tracked after the visitor has navigated away from the page. The solution is to disable automatic tracking and manually trigger pageviews using Turbolinks' own navigation event.
Adding the Fathom script
Add the Fathom script to your site's head with data-auto="false" to disable automatic tracking:
<script src="https://cdn.usefathom.com/script.js" data-site="YOUR-SITE-ID" data-auto="false" defer></script>Note: Replace `YOUR-SITE-ID` with your actual Fathom site ID. Do not include `data-spa="auto"` as Turbolinks handles navigation differently.
Triggering pageviews on navigation
Add this JavaScript to your site to track pageviews on Turbolinks navigation. The turbolinks:load event fires on the initial page load and after every Turbolinks navigation:
document.addEventListener('turbolinks:load', function() { if (window.fathom) { window.fathom.trackPageview(); }});Complete example
Here's everything together:
<script src="https://cdn.usefathom.com/script.js" data-site="YOUR-SITE-ID" data-auto="false" defer></script> <script> document.addEventListener('turbolinks:load', function() { if (window.fathom) { window.fathom.trackPageview(); } });</script>Using Turbo (Hotwire) instead?
If you're using Turbo (the successor to Turbolinks, part of Hotwire), use the turbo:load event instead:
document.addEventListener('turbo:load', function() { if (window.fathom) { window.fathom.trackPageview(); }});Troubleshooting
Pageviews are being tracked twice: Make sure you've added data-auto="false" to your script tag. Without this, Fathom tracks the initial pageview automatically, and your event listener tracks it again.
Pageviews aren't being tracked: Check that your site ID is correct, verify the Fathom script is loading in your browser's Network tab, and confirm window.fathom exists in the browser console.
Further customization
To learn about all the options we offer, read our advanced documentation here.