Insert script into header in Next.js using Script component
P粉458913655
P粉458913655 2023-08-25 08:55:35
0
1
406

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?

任何建议都将有所帮助

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 { const initialProps = await Document.getInitialProps(ctx); return { ...initialProps }; } render() { return (        {/* for Zoho Marketing Automation */}  {/* end Zoho marketing automation */}   
); } } export default MyDocument;
P粉458913655
P粉458913655

reply all (1)
P粉818125805

I re-read the previous postNext 11 and adding Script tags not working. No scripts are renderedenter link description hereand 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 */}  {/* for Zoho Marketing Automation */}  {/* 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( <>    ); }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!