From ff1109b633f16011e79acfb4470f479dec110206 Mon Sep 17 00:00:00 2001 From: Janicklas Ralph Date: Tue, 10 Aug 2021 10:41:26 -0700 Subject: [PATCH] Fix `next/script` unhandled promise rejection (#27903) ## Bug - [x] fixes #27747 - [x] Integration tests added --- packages/next/client/script.tsx | 19 ++++++++++--------- test/integration/script-loader/pages/page3.js | 8 ++++++++ .../script-loader/test/index.test.js | 6 ++++++ 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/packages/next/client/script.tsx b/packages/next/client/script.tsx index 8968f0e77b198..782925de8c0cd 100644 --- a/packages/next/client/script.tsx +++ b/packages/next/client/script.tsx @@ -10,8 +10,8 @@ const LoadCache = new Set() export interface ScriptProps extends ScriptHTMLAttributes { strategy?: 'afterInteractive' | 'lazyOnload' | 'beforeInteractive' id?: string - onLoad?: () => void - onError?: () => void + onLoad?: (e: any) => void + onError?: (e: any) => void children?: React.ReactNode } @@ -56,18 +56,19 @@ const loadScript = (props: ScriptProps): void => { const el = document.createElement('script') const loadPromise = new Promise((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) { diff --git a/test/integration/script-loader/pages/page3.js b/test/integration/script-loader/pages/page3.js index 8da988ec50779..7a8a05a9ebf69 100644 --- a/test/integration/script-loader/pages/page3.js +++ b/test/integration/script-loader/pages/page3.js @@ -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" > +