Performance issue with NextJs and GTM

Viewed 370

Recently I have integrated GTM in my NextJs project. Before the integration was done I used to get 96 on lighthouse performance score. After integration, the score came down to 38. Is there any efficient way of integrating GTM without hampering the performance of the website?

My integration as follows - in _document.tsx file:

<Head>
          <link rel="shortcut icon" href="/favicon.ico" />
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
            defer
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
                  page_path: window.location.pathname,
                });
              `
            }}
          />
        </Head>
1 Answers

You might want to do this

import Script from "next/script";
     
     <Head>
      <link rel="shortcut icon" href="/favicon.ico" />
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
        defer
      />
      <Script 
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
              page_path: window.location.pathname,
            });
          `
        }}
      />
    </Head>

consider switching "afterInteractive" with "beforeInteractive" and if that doesn't help you can put the gtag script in footer

Related