From 50da7e8ad4b82a588467d701bd17e702ce723534 Mon Sep 17 00:00:00 2001 From: Nsanjayboruds Date: Sat, 25 Apr 2026 12:27:23 +0530 Subject: [PATCH] perf: clean up GTM init listeners after first successful initialization Signed-off-by: Nsanjayboruds --- gatsby-browser.js | 38 ++++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/gatsby-browser.js b/gatsby-browser.js index 79cf8f29b2440..b7f4f47a95b00 100644 --- a/gatsby-browser.js +++ b/gatsby-browser.js @@ -5,29 +5,51 @@ import "slick-carousel/slick/slick-theme.css"; export const disableCorePrefetching = () => process.env.NODE_ENV === "development"; +const GTM_DELAY_MS = 3500; +const GTM_INIT_EVENTS = ["scroll", "mousemove", "touchstart"]; + +function addInitListeners() { + GTM_INIT_EVENTS.forEach((eventName) => { + document.addEventListener(eventName, initGTMOnEvent); + }); +} + +function removeInitListeners() { + GTM_INIT_EVENTS.forEach((eventName) => { + document.removeEventListener(eventName, initGTMOnEvent); + }); +} + document.addEventListener("DOMContentLoaded", () => { - /** init gtm after 3500 seconds - this could be adjusted */ - setTimeout(initGTM, 3500); + // Initialize GTM after a short delay unless user interaction triggers it first. + setTimeout(initGTM, GTM_DELAY_MS); }); -document.addEventListener("scroll", initGTMOnEvent); -document.addEventListener("mousemove", initGTMOnEvent); -document.addEventListener("touchstart", initGTMOnEvent); -function initGTMOnEvent(event) { + +addInitListeners(); + +function initGTMOnEvent() { initGTM(); - event.currentTarget.removeEventListener(event.type, initGTMOnEvent); // remove the event listener that got triggered } + function initGTM() { if (window.gtmDidInit) { return false; } + window.gtmDidInit = true; // flag to ensure script does not get added to DOM more than once. + removeInitListeners(); + const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; // ensure PageViews is always tracked (on script load) script.onload = () => { window.dataLayer = window.dataLayer || []; - window.dataLayer.push({ event: "gtm.js", "gtm.start": new Date().getTime(), "gtm.uniqueEventId": 0 }); + window.dataLayer.push({ + event: "gtm.js", + "gtm.start": new Date().getTime(), + "gtm.uniqueEventId": 0, + }); }; script.src = "https://www.googletagmanager.com/gtm.js?id=GTM-PS26QB9"; document.head.appendChild(script);