Search code examples
javascriptnode.jsreactjsnext.jspreload

How to preload a script in nextjs?


I am trying to add a script in my website.

The problem is the script doesn't load the first time the page renders after a couple of refreshes it works and the iFrame it's responsible for shows up.

I tried a few different ways but nothing worked

Here is the code:

_app.js

      <Script
        src="https://boards.greenhouse.io/embed"
        onError={(e) => {
          console.error('Script failed to load', e)
        }}
      />

Notice that onError doesn't show any error either.

I also tried loading it in the component itself like but still doesn't work

 useEffect(() => {
    console.log("lets go");
    <Script src="https://boards.greenhouse.io/embed" />
  }, []);

I gave it the strategy attribute and tried all the values it can have but that didn't work either.


Solution

  • The page I was loading the script on was being navigated using

    <Link href=""></Link>
    

    I had to replace it with

    <a href=""></a>
    

    and it worked, hope it helps.