Insert script into header in Next.js using Script component
P粉458913655
2023-08-25 08:55:35
<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>
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.
My _app.tsx file is as follows: