'How to reduce the impact of third-party code in Next.js?

How can I reduce the impact of third-party code in my next.js app? I am using google analytics and google adsense code on my website. And I am getting performance issues.

see this image

_document.js

import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html>
        <Head>
          <script
            defer
            src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GA_ID}`}
          />
          <script
            defer
            dangerouslySetInnerHTML={{
              __html: `
                                window.dataLayer = window.dataLayer || [];
                                function gtag(){dataLayer.push(arguments);}
                                gtag('js', new Date());
                                gtag('config', '${process.env.GA_ID}', {
                                page_path: window.location.pathname,
                                });
                            `,
            }}
          />
          <script
            defer
            src={
              "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-75************"
            }
            crossOrigin="anonymous"
          ></script>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

My website - click here



Solution 1:[1]

You can use the new Next.js Script tag. Check out the documentation and I think you'll learn how to have better management of your scripts.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ali AlHussain