Unverified Commit ed3cb83c authored by Sukka's avatar Sukka Committed by GitHub

next/script: make `onLoad` concurrent rendering resilient (#40191)

Another step toward fixing #40025.

Multiple `next/script` components with the same `src` may exist in the
Next.js app. So the `loadScript` function will always attach the
`onLoad` handler to the `loadingPromise` every time it executes.

However, with strict mode (or wrapped inside the `<OffScreen />`
component), the `useEffect` could execute more than once for the same
`next/script` component, thus the `loadScript` for each `next/script`
component could execute more than once (and `onLoad` to be attached more
than once), results in `onLoad` fires more than once.

The PR makes sure that for every `next/script` component mounted, the
`loadScript` will always be executed only once for each of them.

The corresponding `onload fires correctly` integration test case is also
updated to run in dev mode.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
parent 155a4d5e
...@@ -52,7 +52,8 @@ const loadScript = (props: ScriptProps): void => { ...@@ -52,7 +52,8 @@ const loadScript = (props: ScriptProps): void => {
// Contents of this script are already loading/loaded // Contents of this script are already loading/loaded
if (ScriptCache.has(src)) { if (ScriptCache.has(src)) {
LoadCache.add(cacheKey) LoadCache.add(cacheKey)
// Execute onLoad since the script loading has begun // It is possible that multiple `next/script` components all have same "src", but has different "onLoad"
// This is to make sure the same remote script will only load once, but "onLoad" are executed in order
ScriptCache.get(src).then(onLoad, onError) ScriptCache.get(src).then(onLoad, onError)
return return
} }
...@@ -182,12 +183,13 @@ function Script(props: ScriptProps): JSX.Element | null { ...@@ -182,12 +183,13 @@ function Script(props: ScriptProps): JSX.Element | null {
* 2. hasOnReadyEffectCalled.current is false, but the script hasn't loaded yet (not in LoadCache) * 2. hasOnReadyEffectCalled.current is false, but the script hasn't loaded yet (not in LoadCache)
* onReady is skipped, set hasOnReadyEffectCalled.current to true * onReady is skipped, set hasOnReadyEffectCalled.current to true
* 3. The useEffect for loadScript executes * 3. The useEffect for loadScript executes
* Once the script is loaded, the onReady will be called by then * 4. hasLoadScriptEffectCalled.current is false, loadScript executes
* Once the script is loaded, the onLoad and onReady will be called by then
* [If strict mode is enabled / is wrapped in <OffScreen /> component] * [If strict mode is enabled / is wrapped in <OffScreen /> component]
* 5. The useEffect for onReady executes again * 5. The useEffect for onReady executes again
* 6. hasOnReadyEffectCalled.current is true, so entire effect is skipped * 6. hasOnReadyEffectCalled.current is true, so entire effect is skipped
* 7. The useEffect for loadScript executes again * 7. The useEffect for loadScript executes again
* 8. The script is already loaded/loading, loadScript bails out * 8. hasLoadScriptEffectCalled.current is true, so entire effect is skipped
* *
* - Second mount: * - Second mount:
* 1. The useEffect for onReady executes * 1. The useEffect for onReady executes
...@@ -199,7 +201,7 @@ function Script(props: ScriptProps): JSX.Element | null { ...@@ -199,7 +201,7 @@ function Script(props: ScriptProps): JSX.Element | null {
* 5. The useEffect for onReady executes again * 5. The useEffect for onReady executes again
* 6. hasOnReadyEffectCalled.current is true, so entire effect is skipped * 6. hasOnReadyEffectCalled.current is true, so entire effect is skipped
* 7. The useEffect for loadScript executes again * 7. The useEffect for loadScript executes again
* 8. The script is already loaded, loadScript will bail out * 8. hasLoadScriptEffectCalled.current is true, so entire effect is skipped
*/ */
const hasOnReadyEffectCalled = useRef(false) const hasOnReadyEffectCalled = useRef(false)
...@@ -215,11 +217,17 @@ function Script(props: ScriptProps): JSX.Element | null { ...@@ -215,11 +217,17 @@ function Script(props: ScriptProps): JSX.Element | null {
} }
}, [onReady, id, src]) }, [onReady, id, src])
const hasLoadScriptEffectCalled = useRef(false)
useEffect(() => { useEffect(() => {
if (strategy === 'afterInteractive') { if (!hasLoadScriptEffectCalled.current) {
loadScript(props) if (strategy === 'afterInteractive') {
} else if (strategy === 'lazyOnload') { loadScript(props)
loadLazyScript(props) } else if (strategy === 'lazyOnload') {
loadLazyScript(props)
}
hasLoadScriptEffectCalled.current = true
} }
}, [props, strategy]) }, [props, strategy])
......
/* global _ */
import Script from 'next/script' import Script from 'next/script'
import Link from 'next/link'
const url = const url =
'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js' 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js'
...@@ -6,12 +8,16 @@ const url = ...@@ -6,12 +8,16 @@ const url =
const Page = () => { const Page = () => {
return ( return (
<div class="container"> <div class="container">
<div id="onload-div-1" />
<Link href="/page9">Page 9</Link>
<Script <Script
src={url} src={url}
id="script1" id="script1"
onLoad={() => { onLoad={() => {
// eslint-disable-next-line no-undef document.getElementById('onload-div-1').textContent += _.repeat(
document.getElementById('text').textContent += _.repeat('a', 3) 'a',
3
)
}} }}
></Script> ></Script>
<Script <Script
...@@ -19,7 +25,10 @@ const Page = () => { ...@@ -19,7 +25,10 @@ const Page = () => {
id="script2" id="script2"
onLoad={() => { onLoad={() => {
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
document.getElementById('text').textContent += _.repeat('b', 3) document.getElementById('onload-div-1').textContent += _.repeat(
'b',
3
)
}} }}
></Script> ></Script>
<Script <Script
...@@ -27,7 +36,10 @@ const Page = () => { ...@@ -27,7 +36,10 @@ const Page = () => {
id="script3" id="script3"
onLoad={() => { onLoad={() => {
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
document.getElementById('text').textContent += _.repeat('c', 3) document.getElementById('onload-div-1').textContent += _.repeat(
'c',
3
)
}} }}
></Script> ></Script>
</div> </div>
......
...@@ -3,6 +3,7 @@ import Link from 'next/link' ...@@ -3,6 +3,7 @@ import Link from 'next/link'
const Page = () => { const Page = () => {
return ( return (
<> <>
<Link href="/page4">Page 4</Link>
<Link href="/page8">Page 8</Link> <Link href="/page8">Page 8</Link>
</> </>
) )
......
...@@ -163,21 +163,31 @@ const runTests = (isDev = false) => { ...@@ -163,21 +163,31 @@ const runTests = (isDev = false) => {
}) })
} }
if (!isDev) { it('onload fires correctly', async () => {
it('onload fires correctly', async () => { let browser
let browser try {
try { browser = await webdriver(appPort, '/page4')
browser = await webdriver(appPort, '/page4') await waitFor(3000)
await waitFor(3000)
const text = await browser.elementById('text').text() const text = await browser.elementById('onload-div-1').text()
expect(text).toBe('aaabbbccc')
expect(text).toBe('aaabbbccc') // Navigate to different page and back
} finally { await browser.waitForElementByCss('[href="/page9"]')
if (browser) await browser.close() await browser.click('[href="/page9"]')
} await browser.waitForElementByCss('[href="/page4"]')
}) await browser.click('[href="/page4"]')
await browser.waitForElementByCss('#onload-div-1')
const sameText = await browser.elementById('onload-div-1').text()
// onload should only be fired once, not on sequential re-mount
expect(sameText).toBe('')
} finally {
if (browser) await browser.close()
}
})
if (!isDev) {
it('priority beforeInteractive with inline script', async () => { it('priority beforeInteractive with inline script', async () => {
const html = await renderViaHTTP(appPort, '/page5') const html = await renderViaHTTP(appPort, '/page5')
const $ = cheerio.load(html) const $ = cheerio.load(html)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment