Skip to content Skip to sidebar Skip to footer

How To Use Next/Head To Render A Script

As I understand from my SO question , I can use next/head to embed a script tag within a component of my React / Next JS app. So, I went about it as such: import React, { Component

Solution 1:

in your _document.js, try to add script below <NextScript /> tag

<body>
   <Main />
   <NextScript />
   <script
        class="3758abc"
        type="text/javascript"
        src="https://cdn2.fake.com/Scripts/embed-button.min.js"
        data-encoded="1234sdkljfeiASD9A"></script>
</body>

Solution 2:

I've been working on a similar issue.

I tried the answer above that places the <script> tag within the <body>, but unfortunately it also rendered the contents generated by the <script> tag to the DOM (as in, it ran the script correctly but also stored all the extra data from it at the bottom of the <body> tag).

I also tried wrapping the script within a <Head> component from next/head (still inside the body), which prevented the DOM rendering, but that fix didn't run the script at all.

In the end, what worked for my use case was moving the script loading into the _app.js file: it runs the script correctly without rendering extra stuff to the DOM. It looks like this:

import Head from "next/head";

function MyApp({ Component, pageProps }) {
  return (
    <React.Fragment>
      <Head>
        <script
          id="my-script"
          src="https://scriptsource.com/script"
          type="text/javascript"
        ></script>
      </Head>

      <LayoutComponent {...pageProps}>
        <Component {...pageProps} />
      </LayoutComponent>
    </React.Fragment>
  );
}

export default MyApp;

I don't know if this solution causes any undesirable effects that I don't know about, but so far it has fixed my issue.


UPDATE (June 2021)

As Ahmed noted below, there are some side effects to the solution I wrote above. What I noticed was that the image loading was being blocked by the script executing.

I saw that Next 11 had just been released, which included the new <Script> tag for this purpose.

I moved all the props into the tag, set strategy="beforeInteractive" and then put this tag into the Page component directly; now everything is running exactly as expected.

Here are the docs for the Next 11 Script tag: https://nextjs.org/docs/basic-features/script


Post a Comment for "How To Use Next/Head To Render A Script"