Skip to content

Commit

Permalink
Fix next/script unhandled promise rejection (#27903)
Browse files Browse the repository at this point in the history
## Bug

- [x] fixes #27747
- [x] Integration tests added
  • Loading branch information
janicklas-ralph committed Aug 10, 2021
1 parent eb871d3 commit 43393d5
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
19 changes: 10 additions & 9 deletions packages/next/client/script.tsx
Expand Up @@ -10,8 +10,8 @@ const LoadCache = new Set()
export interface ScriptProps extends ScriptHTMLAttributes<HTMLScriptElement> {
strategy?: 'afterInteractive' | 'lazyOnload' | 'beforeInteractive'
id?: string
onLoad?: () => void
onError?: () => void
onLoad?: (e: any) => void
onError?: (e: any) => void
children?: React.ReactNode
}

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

const loadPromise = new Promise<void>((resolve, reject) => {
el.addEventListener('load', function () {
el.addEventListener('load', function (e) {
resolve()
if (onLoad) {
onLoad.call(this)
onLoad.call(this, e)
}
})
el.addEventListener('error', function () {
reject()
if (onError) {
onError()
}
el.addEventListener('error', function (e) {
reject(e)
})
}).catch(function (e) {
if (onError) {
onError(e)
}
})

if (src) {
Expand Down
8 changes: 8 additions & 0 deletions test/integration/script-loader/pages/page3.js
Expand Up @@ -15,6 +15,14 @@ const Page = () => {
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptLazyOnload"
strategy="lazyOnload"
></Script>
<Script
src="https://example.com/doesntexist"
strategy="lazyOnload"
onError={(e) => {
console.log('error')
console.log(e)
}}
/>
<div>page3</div>
</div>
)
Expand Down
6 changes: 6 additions & 0 deletions test/integration/script-loader/test/index.test.js
Expand Up @@ -69,6 +69,12 @@ describe('Script Loader', () => {
await browser.waitForElementByCss('#onload-div')
await waitFor(1000)

const logs = await browser.log('browser')
const filteredLogs = logs.filter(
(log) => !log.message.includes('Failed to load resource')
)
expect(filteredLogs.length).toBe(0)

async function test(id) {
const script = await browser.elementById(id)
const endScripts = await browser.elementsByCss(
Expand Down

0 comments on commit 43393d5

Please sign in to comment.