Reduce unused JavaScript from GTM script

Viewed 1655

As stated in the Google Tag Manager docs, I include the GTM JavaScript inside the <head> tag of my Next.js site like so:

// pages/_app.js

  return (
    <>
      <Head>
      <script dangerouslySetInnerHTML={{ __html: `(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-xxxxxx');`  }}></script>
      </Head>
...

Doing so gives a warning on Google PageSpeed Insights:

enter image description here

Any advice?

2 Answers

You should really keep in mind that the Google page speed insights are pretty generic. They are not the last instance of truth in the world. While it's useful for a lot of sites, it's meant to give you insight into what it calculated may be useful to do. Pretty generic calculations.

Yes, Google lighthouse tends to frown upon TMSes. Maybe cuz they tend to override some native methods, maybe cuz TMses have evals in them, maybe due to the number of event listeners they deploy immediately on init. If you want to look into a TMS performance, you can compare the performance results with an empty GTM container versus your actual container. If that difference is real and significant, then maybe it's time to start optimizing GTM logic.

Render blocking issue can be solved using wp rocket. Because it hasthis option to eliminate these blocking.

Related