Tracking Scripts
In our setup, we consistently use Google Tag Manager (GTM) as the main container for tracking, with analytics connected through it.
To ensure accurate tracking during page transitions—since there is no full page reload we push a virtual pageview event to the dataLayer every time a page changes. This allows Google Analytics to properly track these transitions.
Init
When using Boostify, we also need to ensure that Google tracking scripts are loaded a few seconds after the page load fired to account for any potential delays. To handle this, we use a helper function that checks if Google Scripts are available, and if so, triggers the GTM event after a short delay:
// At Project.js you should have something like this in Constructorboostify.onload({ maxTime:1200,})
/** * Google Scripts * Since we are using Boostify, we need to verify if the Google Scripts have been loaded a few seconds after the page is loaded. * If they are detected, we trigger the GTM script. * This setup is necessary because page transitions are used, requiring a custom event to correspond with a page view in GTM after each page change. */
async init(){ const { hasGoogleScripts } = await import('@terrahq/helpers/hasGoogleScripts'); this.detected = await hasGoogleScripts({ maxTime: 1201 }); if (this.detected) { window.dataLayer.push({ event: 'VirtualPageview', virtualPageURL: window.location.pathname + window.location.search, virtualPageTitle: document.title }); } else { this.terraDebug ? console.log("Google Scripts not detected") : null; }}
This logic is placed inside the init function in the Core class, ensuring that the check for Google Scripts is run only once during the initial load. This method is particularly important when dealing with page transitions, as each page change must trigger a virtual pageview event to ensure tracking remains accurate.
This ensures that Google Analytics is properly tied to every page transition and that Boostify’s interaction with GTM is handled seamlessly
Events
In the events
function, we trigger a virtual pageview event whenever a new page is replaced:
events() {
/** * This project uses page transitions, requiring a custom event to be triggered after each page change to ensure that a page view is recorded in Google Tag Manager (GTM). */ this.swup.hooks.on("page:view", async () => { if(this.detected){ window.dataLayer.push({ event: "VirtualPageview", virtualPageURL: window.location.pathname + window.location.search, virtualPageTitle: document.title, }); } });}