The above is the error message that comes when the script tag doesn't load. I have around 6 script tags.
I have these Scripts tags in my code; sometimes they load and sometimes they don't. But I can see them in the code if I inspect them in the browser.
<Script src="assets/js/jquery-3.5.1.min.js" strategy="beforeInteractive" />
<Script src="assets/js/bootstrap.bundle.min.js" strategy="beforeInteractive" />
I have included them in pages/_app.js and pages/_document.js, and also in some other pages just to test out but they don't work correctly.
Only after I refresh the page then they start working correctly.
OS: Linux
on windows they load properly. only on Linux I'm having this issue.
Can someone help me out with this as I need this thing resolved Quickly?
Appriciate your help.
The jQuery loaded by the <Script /> component (without beforeInteractive) will certainly not be available when React hydrates your page by default (If it is available during useEffect, then it is a bug and you should report it to Next.js).
<Script /> component is designed to handle non-essential scripts for you (E.g., Google Analytics is only essential for website owners, but not essential for rendering the page). Thus Next.js will never load the script before React hydrates your page, resulting in a better performance and user experience.
In this case, jQuery should be considered an essential script for rendering the page, thus it shouldn't be loaded through <Script />.
I would recommend the following approaches:
import $ from 'assets/js/jquery-3.5.1.min.js';
import 'assets/js/bootstrap.bundle.min.js';
beforeInteractiveNote: <Script strategy="beforeInteractive" /> can only be used inside a custom _document!
// _document.jsx
import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
{/** You can place it everywhere as long as it is inside a custom _document */}
{/** And Next.js will always inject the script to the <head /> */}
<Script
src="assets/js/jquery-3.5.1.min.js"
strategy="beforeInteractive"
></Script>
</body>
</Html>
)
}
More details about <Script /> component: https://nextjs.org/docs/basic-features/script
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With