Ultimate Guide to Implementing the gtag API: Top Solutions & Steps

Jennie Lee
5 min readApr 13, 2024

--

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

Introduction

This article aims to provide a comprehensive guide on how to implement the gtag API to track subsequent page visits on a Turbolinks-powered site. By default, Google Analytics’ gtag.js code only tracks the initial page visit on traditional multi-page websites. However, when using Turbolinks, which is a JavaScript library for faster page navigation, additional steps are required to ensure that subsequent page visits are accurately recorded in Google Analytics.

Understanding how to properly implement the gtag API with Turbolinks is essential for website owners and developers who want to track user behavior across all pages of their Turbolinks-powered site. By following the steps and guidelines provided in this guide, you will be able to track page views and gain valuable insights into user engagement and website performance.

Understanding Google Analytics and Turbolinks

Google Analytics is a powerful web analytics tool that allows website owners to track various metrics, including page views, user demographics, and conversion rates. By default, the gtag.js tracking code provided by Google Analytics is designed to track page views on traditional multi-page websites.

Turbolinks, on the other hand, is a JavaScript library that enhances page navigation by dynamically loading content and replacing only the necessary parts of a page when a user clicks on a link. It reduces the need for full page reloads, resulting in faster and smoother navigation.

The challenge arises when using the default gtag.js code with Turbolinks. Since Turbolinks dynamically updates the content of a page without triggering a full page reload, the gtag.js code does not capture subsequent page visits. This limitation can lead to inaccurate data and incomplete tracking of user behavior on Turbolinks-powered sites.

Implementing Google Analytics with Turbolinks using the gtag API

To overcome the limitations of the default gtag.js code and track subsequent page visits on a Turbolinks-powered site, the gtag API can be used. The gtag API is a JavaScript API provided by Google Analytics that allows developers to programmatically send page views and other data to Google Analytics.

To implement Google Analytics with Turbolinks using the gtag API, follow these steps:

  1. Copy the Global Site Tag (gtag.js) code from the Google Analytics dashboard. The code should be placed as the first item inside the <head> tag of your website.
  2. Replace the default tracking code with your website’s Analytics ID. The tracking code typically looks like UA-XXXXXXXX-X, where XXXXXXXX-X represents your unique Analytics ID.
  3. Below the script tag containing the Analytics code, add another script tag. This script listens for the Turbolinks:load event, which is fired when a new page is loaded via Turbolinks. Inside this script, we will send a page view to Google Analytics.

Here is an example of the implementation code:

<head>
<!-- Global Site Tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=YOUR_ANALYTICS_ID"></script>

<!-- Turbolinks gtag.js integration -->
<script>
document.addEventListener('turbolinks:load', function() {
gtag('config', 'YOUR_ANALYTICS_ID', {
'page_path': location.pathname
});
});
</script>
</head>

Replace YOUR_ANALYTICS_ID with your actual Analytics ID. This code will ensure that Turbolinks sends a page view event to Google Analytics whenever a new page is loaded.

Understanding the Code

To understand how the code works, let’s take a closer look at each component and its role in the implementation:

gtag.js script

The gtag.js script is loaded asynchronously from Google’s servers. It initializes the Analytics script and provides a global gtag() function that can be used to push data to the dataLayer array.

gtag() function

The gtag() function is the key component for sending data to Google Analytics. It accepts different arguments depending on the type of data being sent. In our implementation, we use the config argument to send the page view event.

Turbolinks:load event

The Turbolinks:load event fires whenever a new page is loaded via Turbolinks. We listen to this event and execute the code inside the event listener function. This ensures that the page view event is sent to Google Analytics whenever a new page is loaded.

Differentiating between initial and subsequent page loads

Inside the event listener function, we first check if it is the initial page load. This is important because we want to ensure that the initial page view is captured separately. If it is the initial page load, we simply return early and let the default gtag.js code handle the tracking.

On subsequent page loads, we call the gtag() function with the config argument, our Analytics ID, and a config object that includes the page_path property. This tells Google Analytics to track the current page based on its URL path.

Handling Page Views and User Experience

One common question is why not track all page views from within the Turbolinks:loaded callback. The reason is that on slow connections, there may be a delay in page loading and Turbolinks initialization. If a user bounces before Turbolinks completes its loading process, the gtag() function inside the Turbolinks:loaded callback would never fire.

By having the first gtag() function right when the page loads, we increase the likelihood of capturing the initial page view. Subsequent page views, handled by the Turbolinks:load event, ensure that all subsequent page visits are accurately tracked.

It is worth noting that using Turbolinks with Google Analytics requires careful consideration of the user experience. While Turbolinks provides faster page navigation, it may create a perceived delay when navigating between pages due to the dynamic content loading process. This delay can affect the accuracy of tracking subsequent page visits.

To ensure a seamless user experience, it is recommended to monitor and test the implementation thoroughly to mitigate any potential issues related to slow connections and Turbolinks initialization.

Conclusion

Implementing the gtag API with Turbolinks allows website owners and developers to accurately track subsequent page visits on Turbolinks-powered sites. By following the step-by-step guide and understanding the code implementation, you can ensure that Google Analytics captures all page views and provides valuable insights into user behavior and website performance.

Tracking subsequent page visits is crucial for gaining a comprehensive understanding of user engagement and optimizing your website’s performance. With the gtag API and Turbolinks integration, you can unlock the full potential of Google Analytics on your Turbolinks-powered site.

I hope this guide has provided you with the knowledge and tools necessary to implement the gtag API successfully. Happy tracking!

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

--

--

Jennie Lee
Jennie Lee

Written by Jennie Lee

Software Testing Blogger, #API Testing

No responses yet