How to conditionally render <Script /> component #62646
SummaryWe have a script we wanted to load on all of our pages, using <Script/> component. We initially placed it in How to handle it by loading the script in We tried loading it conditionally inside Additional informationNo response ExampleNo response |
Replies: 4 comments
|
Same question here... |
|
A conditional If the goal is "do not load it until one of these routes is visited", an allow-list in import Script from "next/script"
import { useRouter } from "next/router"
const routesWithVendor = new Set(["/checkout", "/account"])
export default function MyApp({ Component, pageProps }) {
const { pathname } = useRouter()
return (
<>
<Component {...pageProps} />
{routesWithVendor.has(pathname) && (
<Script
id="vendor-script"
src="https://example.com/vendor.js"
strategy="afterInteractive"
/>
)}
</>
)
}After a visitor leaves https://nextjs.org/docs/pages/api-reference/components/script |
|
thanks change |
|
thanks2 |
A conditional
<Script>in_appcan control when the script is first injected, but it cannot undo a script that has already loaded._apppersists across client-side navigation, and the third-party code may have already registered globals, listeners, or DOM changes. Removing the React component on the next route does not reverse those effects.If the goal is "do not load it until one of these routes is visited", an allow-list in
_appis fine: