Skip to main content

Improve score by deferring GTM

Google Tag Manager (GTM) is one of the most common reasons for a low PageSpeed score. By default, GTM loads immediately and blocks page rendering, which negatively affects performance metrics like Largest contentful paint (LCP) and Total blocking time (TBT). You can significantly improve your score by deferring GTM loading - making it load a few seconds after the page has finished rendering. This way, your visitors see the page content first, and tracking scripts load quietly in the background.

How to set it up

  1. Go to Admin > Stores > Configuration > Mirasvit Extensions > Google Tag Manager > General
  2. Find the GTM Code (Regular) field
  3. Replace the standard GTM snippet with the deferred version below
  4. Save the configuration and flush the cache

Standard GTM code (before)

<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({"gtm.start":
new Date().getTime(),event:"gtm.js"});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!="dataLayer"?"&l="+l:"";j.async=true;
j.src="https://www.googletagmanager.com/gtm.js?id="+i+dl;
f.parentNode.insertBefore(j,f);
})(window,document,"script","dataLayer","GTM-XXXXXXX");
</script>

Deferred GTM code (after)

<script>
(function(w,d,s,l,i){
function loadGTM() {
w[l]=w[l]||[];w[l].push({"gtm.start":new Date().getTime(),event:"gtm.js"});
var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!="dataLayer"?"&l="+l:"";
j.async=true;j.src="https://www.googletagmanager.com/gtm.js?id="+i+dl;
f.parentNode.insertBefore(j,f);
}
if(d.readyState==="complete"){setTimeout(loadGTM,3000);}
else{w.addEventListener("load",function(){setTimeout(loadGTM,3000);});}
})(window,document,"script","dataLayer","GTM-XXXXXXX");
</script>
note

Replace GTM-XXXXXXX with your actual GTM container ID.

What this does

  • Waits until the page is fully loaded
  • Then waits an additional 3 seconds before loading GTM
  • All tracking still works - events are queued and processed once GTM loads

Adjusting the delay

The 3000 value is the delay in milliseconds (3 seconds). You can adjust this:

  • 2000: 2 seconds (faster tracking, slightly less PageSpeed benefit)
  • 5000: 5 seconds (better PageSpeed score, but longer delay before tracking starts)

For most stores, 3 seconds is the best balance between performance and tracking accuracy.

note

This change only affects how quickly GTM starts loading. All page views and events will still be tracked correctly.