score:41

Accepted answer

this works to me:

create a folder for your static files:

<root>/static/hello.js

in your index.js

<root>/pages/index.js

import head from 'next/head';
import myawesomecomponent from '../components/mycomponent';

export default () => (
  <div>
    <head>
      <script type="text/javascript" src="/static/hello.js"></script>
    </head>
    <myawesomecomponent />
  </div>
)

hope this help,

regards

score:0

i wrote an article elaborating on this question, hopefully it comes in handy:

https://www.devtwins.com/blog/how-to-add-a-third-party-script-to-a-nextjs-website

score:1

this is what i tried and it worked for me. i used two files entry-script.js and main-script.js. i put these like this <root>/static/entry-script.js and <root>/static/main-script.js the content of entry-script.js is below.

(function (d, t) {
  t = d.createelement("script");
  t.setattribute("src", "/static/main-script.js");
  d.getelementsbytagname("head")[0].appendchild(t);
})(document);

and the main logic is in the file main-script.js. in the file _doucment.js of nextjs i included my file entry-script.js in body like below

class mydocument extends document {
  render() {
    return (
      <html>
        <head>
          <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css?family=roboto:300,400,500,700&display=swap"
          />
        </head>
        <body>
          <script
            type="text/javascript"
            src="/static/entry-script.js"
          ></script>
          <main />
          <nextscript />
        </body>
      </html>
    );
  }
}

export default mydocument;

mydocument.getinitialprops = async (ctx) => {
  // resolution order
  //
  // on the server:
  // 1. app.getinitialprops
  // 2. page.getinitialprops
  // 3. document.getinitialprops
  // 4. app.render
  // 5. page.render
  // 6. document.render
  //
  // on the server with error:
  // 1. document.getinitialprops
  // 2. app.render
  // 3. page.render
  // 4. document.render
  //
  // on the client
  // 1. app.getinitialprops
  // 2. page.getinitialprops
  // 3. app.render
  // 4. page.render

  // render app and page and get the context of the page with collected side effects.
  const sheets = new serverstylesheets();
  const originalrenderpage = ctx.renderpage;

  ctx.renderpage = () =>
    originalrenderpage({
      enhanceapp: (app) => (props) => sheets.collect(<app {...props} />),
    });

  const initialprops = await document.getinitialprops(ctx);

  return {
    ...initialprops,
    // styles fragment is rendered after the app and page rendering finish.
    styles: [
      ...react.children.toarray(initialprops.styles),
      sheets.getstyleelement(),
    ],
  };
};

score:4

may this helps you nextjs public folder

move your static folder into public folder in your root directory

export default () => (
    <div>
      <head>

        <link type="text/css" rel="stylesheet" href="/static/css/chatwidget.css" />
        <link type="text/css" rel="stylesheet" href="/static/css/download.css" />

        <script type="text/javascript" src="/static/libs/jquery.min.js"></script>
        ...
      </head>

      <myawesomecomponent /> 
    </div>
  )

score:6

with next.js v11, you can use the next component script

https://nextjs.org/blog/next-11#script-optimization

<script
  src="..."
  strategy="beforeinteractive"
/>

score:19

you can also run js code this

          <script
            dangerouslysetinnerhtml={{
              __html: `
                      let a = 1;
                      functioncall();
                  `,
            }}
          ></script>

score:23

with the below approach you can easily put a script file's raw script text into a generated next.js html page's <head> without screwing around with character escaping, formatting and general pretending that we aren't actually just building an html page in the end anyways.

there are many use cases you may want a script to run without going to network. ex: 3rd party scripts, monitoring / analytics scripts that expect to be in the <head> without a separate network load. many of these come minified, mangled, you-name-it and are just supposed to be copy, paste, move on with life.

next.js makes this very hard pretending that everything with web development is magically react and webpack all the time now (i wish right?)

the best developer experience way i've found is to do this:

_document.js

...
<head>
  <script type="text/javascript" dangerouslysetinnerhtml={{ __html: process.env.rawjsfromfile }}></script>
</head>
...

next.config.js

https://github.com/vercel/next.js/blob/canary/packages/next/next-server/server/config.ts#l33

module.exports = {
  env: {
    rawjsfromfile: fs.readfilesync('./rawjsfromfile.js').tostring()
  }
}

rawjsfromfile.js

alert('freedom!!!!!!!!!!!!!!!');
// and other 3rd party script junk, heck even minified js is fine too if you need

hope this saves someone from hours of frustration that i endured coming up with this... 😭


Related Query

More Query from same tag