DEV Community

Angrej Kumar
Angrej Kumar

Posted on

Google TagManager snippet is affecting total block time in pageinsights

In my NextJS application I have added google tag manager embed code like this in a separate component and then I call this component in _app.tsx, but when I add this my https://pagespeed.web.dev/ Total Blocking Time increased. I think google tag manager is loading asynchronously, but not me for me I think. Not sure what wrong I'm doing.

"use client"

import { GTM_ID, pageview } from "@/lib/gtm"
import { usePathname, useSearchParams } from "next/navigation"
import Script from "next/script"
import { useEffect } from "react"

export default function Analytics() {
  const pathname = usePathname()
  const searchParams = useSearchParams()

  useEffect(() => {
    if (pathname) {
      pageview(pathname)
    }
  }, [pathname, searchParams])

  if (process.env.NODE_ENV !== "production") {
    return null
  }

  return (
    <>
      <noscript>
        <iframe
          src={`https://www.googletagmanager.com/ns.html?id=${GTM_ID}`}
          height="0"
          width="0"
          style={{ display: "none", visibility: "hidden" }}
        />
      </noscript>
      <Script
        id="gtm-script"
        strategy="afterInteractive"
        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_ID}');
  `,
        }}
      />
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Can please some help? I'm using NextJS 13.3

Top comments (0)