Problem

When adding a tracking code (e.g. Google Analytics, Google Ads, Facebook Pixel etc.) to the website, instructions say:

Add the code to all pages.

It worked right for many years. The code was part of the main website template and therefore present on all the pages. When a page was loaded, tracking code was called. Everything worked as expected.

But then, AJAX and SPA (single-page application) websites came. Because these AJAX pages load the whole page just once and then all the subsequent content changes are done via AJAX requests, therefore the tracking code is called only once.

It results in tracking of only the first pageview and other problems (e.g. with dynamic remarketing).

Solution

All tracking codes that are meant to be on all pages, must be called every time the page content is changing. It means tracking codes must be called on an event.

There are two options of triggering an event:

  1. The Google Tag Manager event is explicitly fired by the website after page content change (i.e. a piece of Google Tag Manager dataLayer code must be called).
  2. The website triggers window.history event and Google Tag Manager (GTM) listens to this change.

And this GTM event must be connected to the Google Analytics Pageview, Google Ads dynamic remarketing or similar tags.

How?

Option 1: Explicitly triggered event

Web developer must add a piece of javascript code that is triggered every time a page (new content) is loaded. Typically, a code can look like this:

dataLayer.push({
    'event':'gaVirtualPageview',
    'gaVirtualPageviewUrl':'/page-url',
    'gaVirtualPageviewTitle':'Page name (title)'
});   

In Google Tag Manager: Then you

  • create appropriate event and DataLayer variables
  • add a Google Analytics Pageview tag pushing the data from DataLayer to Google Analytics

Option 2: Listening to window.history change

This option does not require a support from a web developer. It uses the GTM ability to catch (listen to) an anchor change.

With this approach you can use:

  • New History Fragment variable
  • History change trigger (instead of custom gaVirtualPageview event trigger)