Home  >  Q&A  >  body text

Insert script into header in Next.js using Script component

<p>I want to insert tracking code from an application called Zoho in the Head section of every page of my Next.js application. I'm using a file called _document.tsx and it works fine. For a skewed script, Next.js recommends using the Next.js Script component (https://nextjs.org/docs/messages/no-script-tags-in-head-component). I followed the instructions and inserted the script into brackets, but it was ignored without an error message.Can I enter this code in the Head section of the _document.tsx file? Would it be better to split it into a separate component?</p> <p>任何建议都将有所帮助</p> <pre class="brush:php;toolbar:false;">import Document, { Html, Head, Main, NextScript, DocumentContext, DocumentInitialProps, } from "next/document"; import Script from "next/script"; class MyDocument extends Document { static async getInitialProps( ctx: DocumentContext ): Promise<DocumentInitialProps> { const initialProps = await Document.getInitialProps(ctx); return { ...initialProps }; } render() { return ( <Html lang="en"> <Head> <meta charSet="utf-8" /> <link href="https://fonts.googleapis.com/css?family=PT Sans&display=optional" rel="stylesheet" /> <meta name="msapplication-TileColor" content="#596285" /> <meta name="msapplication-config" content="/favicon/browserconfig.xml" /> <meta name="theme-color" content="#ffffff" /> {/* for Zoho Marketing Automation */} <Script id="zoho-ma"> {`var w = window; var p = w.location.protocol; if (p.indexOf("http") < 0) { p = "http" ":"; } var d = document; var f = d.getElementsByTagName("script")[0], s = d.createElement("script"); s.type = "text/javascript"; s.async = false; if (s.readyState) { s.onreadystatechange = function () { if (s.readyState == "loaded" || s.readyState == "complete") { s.onreadystatechange = null; try { loadwaprops( "myid#", "myid#", "myid#", "myid#", "0.0" ); } catch (e) {} } }; } else { s.onload = function () { try { loadwaprops( "myid#", "myid#", "myid#", "myid#", "0.0" ); } catch (e) {} }; }s.src = p "//ma.zoho.com/hub/js/WebsiteAutomation.js"; f.parentNode.insertBefore(s, f);`} </Script> {/* end Zoho marketing automation */} </Head> <body> <Main /> <NextScript /> <div id="notifications"></div> </body> </Html> ); } } export default MyDocument;</pre>
P粉458913655P粉458913655389 days ago447

reply all(1)I'll reply

  • P粉818125805

    P粉8181258052023-08-26 00:03:41

    I re-read the previous postNext 11 and adding Script tags not working. No scripts are rendered enter link description here and realized you can't put < Script> component is placed in the Head tag. Also, it should not be in _document.tsx but in _app.tsx (unless you use beforeInteractive, see link above).

    Because I also wanted to include the Google Analytics script, I created a component called TrackingCode as a separate js file.

    import Script from "next/script";
    
    function TrackingCode() {
      return (
       <>
      {/* Global site tag (gtag.js) - Google Analytics */}
      <Script src="https://www.googletagmanager.com/gtag/js?id=G-GOOGLEID" />
      <Script id="google-analytics" strategy="afterInteractive">
        {`
      window.dataLayer = window.dataLayer || [];
      function gtag(){window.dataLayer.push(arguments);}
      gtag('js', new Date());
    
      gtag('config', 'G-GOOGLEID');
      `}
      </Script>
    
      {/* for Zoho Marketing Automation */}
    
      <Script id="zoho-ma">
        {`var w = window;
    var p = w.location.protocol;
    if (p.indexOf("http") < 0) {
      p = "http" + ":";
    }
    var d = document;
    var f = d.getElementsByTagName("script")[0],
      s = d.createElement("script");
    s.type = "text/javascript";
    s.async = false;
    if (s.readyState) {
      s.onreadystatechange = function () {
        if (s.readyState == "loaded" || s.readyState == "complete") {
          s.onreadystatechange = null;
          try {
            loadwaprops(
              "mycode",
              "mycode",
              "mycode",
              "mycode",
              "0.0"
            );
          } catch (e) {}
        }
      };
    } else {
      s.onload = function () {
        try {
          loadwaprops(
            "mycode",
            "mycode",
            "mycode",
             "mycode",
            "0.0"
          );
        } catch (e) {}
      };
    }
    s.src = p + "//ma.zoho.com/hub/js/WebsiteAutomation.js";
    f.parentNode.insertBefore(s, f);`}
      </Script>
      {/* end Zoho marketing automation */}
    </>
     );
    }
    
    export default TrackingCode;

    My _app.tsx file is as follows:

    import "../assets/scss/material-kit.scss";
    import "../node_modules/bootstrap/scss/bootstrap.scss";
    import "../styles/globals.scss";
    import { useEffect } from "react";
    import type { ReactElement, ReactNode } from "react";
    import type { NextPage } from "next";
    import type { AppProps } from "next/app";
    import TrackingCode from "../components/tracking-code";
    
    import store from "../app/store";
    
    
    export type NextPageWithLayout = NextPage & {
      getLayout?: (page: ReactElement) => ReactNode;
    };
    
    type AppPropsWithLayout = AppProps & {
      Component: NextPageWithLayout;
    };
    
    export default function MyApp({ Component, pageProps }: AppPropsWithLayout) 
    {
     const getLayout = Component.getLayout ?? ((page) => page);
      useEffect(() => {
       typeof document !== undefined
          ? require("../node_modules/bootstrap/dist/js/bootstrap")
         : null;
      }, []);
    
    return getLayout(
       <>
         <TrackingCode />
         <Component {...pageProps} />
       </>
      );
    }

    reply
    0
  • Cancelreply