Skip to content
This repository was archived by the owner on Jun 21, 2023. It is now read-only.

Commit ff1109b

Browse files
Fix next/script unhandled promise rejection (vercel#27903)
## Bug - [x] fixes vercel#27747 - [x] Integration tests added
1 parent f8694a2 commit ff1109b

File tree

3 files changed

+24
-9
lines changed

3 files changed

+24
-9
lines changed

packages/next/client/script.tsx

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ const LoadCache = new Set()
1010
export interface ScriptProps extends ScriptHTMLAttributes<HTMLScriptElement> {
1111
strategy?: 'afterInteractive' | 'lazyOnload' | 'beforeInteractive'
1212
id?: string
13-
onLoad?: () => void
14-
onError?: () => void
13+
onLoad?: (e: any) => void
14+
onError?: (e: any) => void
1515
children?: React.ReactNode
1616
}
1717

@@ -56,18 +56,19 @@ const loadScript = (props: ScriptProps): void => {
5656
const el = document.createElement('script')
5757

5858
const loadPromise = new Promise<void>((resolve, reject) => {
59-
el.addEventListener('load', function () {
59+
el.addEventListener('load', function (e) {
6060
resolve()
6161
if (onLoad) {
62-
onLoad.call(this)
62+
onLoad.call(this, e)
6363
}
6464
})
65-
el.addEventListener('error', function () {
66-
reject()
67-
if (onError) {
68-
onError()
69-
}
65+
el.addEventListener('error', function (e) {
66+
reject(e)
7067
})
68+
}).catch(function (e) {
69+
if (onError) {
70+
onError(e)
71+
}
7172
})
7273

7374
if (src) {

test/integration/script-loader/pages/page3.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ const Page = () => {
1515
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptLazyOnload"
1616
strategy="lazyOnload"
1717
></Script>
18+
<Script
19+
src="https://example.com/doesntexist"
20+
strategy="lazyOnload"
21+
onError={(e) => {
22+
console.log('error')
23+
console.log(e)
24+
}}
25+
/>
1826
<div>page3</div>
1927
</div>
2028
)

test/integration/script-loader/test/index.test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,12 @@ describe('Script Loader', () => {
6969
await browser.waitForElementByCss('#onload-div')
7070
await waitFor(1000)
7171

72+
const logs = await browser.log('browser')
73+
const filteredLogs = logs.filter(
74+
(log) => !log.message.includes('Failed to load resource')
75+
)
76+
expect(filteredLogs.length).toBe(0)
77+
7278
async function test(id) {
7379
const script = await browser.elementById(id)
7480
const endScripts = await browser.elementsByCss(

0 commit comments

Comments
 (0)