From 8f68cdfb6650ca22c8128171b37036a595c414b5 Mon Sep 17 00:00:00 2001 From: Tal Hadad Date: Mon, 5 Sep 2022 20:01:37 +0300 Subject: [PATCH] chore: simplify the code --- .../src/node/plugins/importAnalysisBuild.ts | 47 ++++++++----------- 1 file changed, 19 insertions(+), 28 deletions(-) diff --git a/packages/vite/src/node/plugins/importAnalysisBuild.ts b/packages/vite/src/node/plugins/importAnalysisBuild.ts index 74ad4c0065f5c8..5f117e719fd52c 100644 --- a/packages/vite/src/node/plugins/importAnalysisBuild.ts +++ b/packages/vite/src/node/plugins/importAnalysisBuild.ts @@ -91,14 +91,6 @@ function preload( } } - const preloadInImg = () => - new Promise((res) => { - const img = new Image() - img.onerror = () => res() - img.onload = () => res() - img.src = dep - }) - const loadLink = () => { // @ts-ignore const link = document.createElement('link') @@ -114,31 +106,30 @@ function preload( return link } - const waitForLoad = (link: HTMLLinkElement) => { - return new Promise((res, rej) => { - // @ts-ignore - if (__VITE_IS_MODERN__) { + if (isCss) { + // @ts-ignore + if (__VITE_IS_MODERN__) { + return new Promise((res, rej) => { + const link = loadLink() link.addEventListener('load', () => res()) link.addEventListener('error', () => rej(new Error(`Unable to preload CSS for ${dep}`)) ) - } else { - // On legacy browsers, let them a chance to process the newly referred CSS link. - setTimeout(res) - } - }) - } - - const loadLinkAndWait = () => { - return waitForLoad(loadLink()) - } - - if (isCss) { - // @ts-ignore - if (__VITE_IS_MODERN__) { - return loadLinkAndWait() + }) } else { - return preloadInImg().then(loadLinkAndWait) + return new Promise((res) => { + const img = new Image() + img.onerror = () => res() + img.onload = () => res() + img.src = dep + }).then( + () => + new Promise((res) => { + loadLink() + // On legacy browsers, let them a chance to process the newly referred CSS link. + setTimeout(res) + }) + ) } } else { loadLink()