diff --git a/packages/next/client/index.tsx b/packages/next/client/index.tsx index 26a2386dd891ac9..86bdc3f6a275b13 100644 --- a/packages/next/client/index.tsx +++ b/packages/next/client/index.tsx @@ -156,6 +156,7 @@ window.__NEXT_P = [] const headManager: { mountedInstances: Set updateHead: (head: JSX.Element[]) => void + getIsSsr?: () => boolean } = initHeadManager() const appElement: HTMLElement | null = document.getElementById('__next') @@ -163,6 +164,9 @@ let lastRenderReject: (() => void) | null let webpackHMR: any export let router: Router let CachedApp: AppComponent, onPerfEntry: (metric: any) => void +headManager.getIsSsr = () => { + return router.isSsr +} class Container extends React.Component<{ fn: (err: Error, info?: any) => void diff --git a/packages/next/client/script.tsx b/packages/next/client/script.tsx index bd26a8b85733705..302991bf3468158 100644 --- a/packages/next/client/script.tsx +++ b/packages/next/client/script.tsx @@ -140,7 +140,7 @@ function Script(props: ScriptProps): JSX.Element | null { } = props // Context is available only during SSR - const { updateScripts, scripts } = useContext(HeadManagerContext) + const { updateScripts, scripts, getIsSsr } = useContext(HeadManagerContext) useEffect(() => { if (strategy === 'afterInteractive') { @@ -161,7 +161,10 @@ function Script(props: ScriptProps): JSX.Element | null { }, ]) updateScripts(scripts) - } else { + } else if (getIsSsr && getIsSsr()) { + // Script has already loaded during SSR + LoadCache.add(restProps.id || src) + } else if (getIsSsr && !getIsSsr()) { loadScript(props) } } diff --git a/packages/next/shared/lib/head-manager-context.ts b/packages/next/shared/lib/head-manager-context.ts index 6a0c85acfbd741d..7388a1da7b09623 100644 --- a/packages/next/shared/lib/head-manager-context.ts +++ b/packages/next/shared/lib/head-manager-context.ts @@ -5,6 +5,7 @@ export const HeadManagerContext: React.Context<{ mountedInstances?: any updateScripts?: (state: any) => void scripts?: any + getIsSsr?: () => boolean }> = React.createContext({}) if (process.env.NODE_ENV !== 'production') { diff --git a/test/integration/script-loader/pages/page3.js b/test/integration/script-loader/pages/page3.js index 58453214b172866..592bd84b16fea02 100644 --- a/test/integration/script-loader/pages/page3.js +++ b/test/integration/script-loader/pages/page3.js @@ -4,11 +4,10 @@ const Page = () => { return (