From f6f6ba4f7ba3cc3858c0f431a118bc88b303e571 Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Mon, 15 Aug 2022 13:41:30 -0700 Subject: [PATCH] feat: direct dynamic import (#327) --- README.md | 8 ++-- rollup.config.js | 2 - src/dynamic-import-csp.js | 36 ----------------- src/dynamic-import.js | 82 ++++++++++++++++++++------------------- src/es-module-shims.js | 3 +- src/features.js | 82 +++++++++++++++++++-------------------- 6 files changed, 87 insertions(+), 126 deletions(-) delete mode 100644 src/dynamic-import-csp.js diff --git a/README.md b/README.md index 728f0de0..3b90206f 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ Shims modern ES Modules features like import maps on top of the baseline modules support in browsers supported by [95% of users](https://caniuse.com/#feat=es6-module). -When running in polyfill mode, [the 67% of users](https://caniuse.com/import-maps) with import maps entirely bypass the shim code entirely. +When running in polyfill mode, [the 72% of users](https://caniuse.com/import-maps) with import maps entirely bypass the shim code entirely. -For the remaining 30% of users, the highly performant (see [benchmarks](#benchmarks)) production and [CSP-compatible](#csp-support) shim kicks in to rewrite module specifiers driven by the [Web Assembly ES Module Lexer](https://github.com/guybedford/es-module-lexer). +For the remaining 28% of users, the highly performant (see [benchmarks](#benchmarks)) production and [CSP-compatible](#csp-support) shim kicks in to rewrite module specifiers driven by the [Web Assembly ES Module Lexer](https://github.com/guybedford/es-module-lexer). The following modules features are polyfilled: @@ -176,8 +176,8 @@ ES Module Shims is designed for production performance. A [comprehensive benchma Benchmark summary: -* [ES Module Shims Chrome Passthrough](bench/README.md#chrome-passthrough-performance) (for [70% of users](https://caniuse.com/import-maps)) results in ~5ms extra initialization time over native for ES Module Shims fetching, execution and initialization, and on a slow connection the additional non-blocking bandwidth cost of its 10KB compressed download as expected. -* [ES Module Shims Polyfilling](bench/README.md#native-v-polyfill-performance) (for the remaining [30% of users](https://caniuse.com/import-maps)) is on average 1.4x - 1.5x slower than native module loading, and up to 1.8x slower on slow networks (most likely due to the browser preloader), both for cached and uncached loads, and this result scales linearly up to 10MB and 20k modules loaded executing on the fastest connection in just over 2 seconds in Firefox. +* [ES Module Shims Chrome Passthrough](bench/README.md#chrome-passthrough-performance) (for [72% of users](https://caniuse.com/import-maps)) results in ~5ms extra initialization time over native for ES Module Shims fetching, execution and initialization, and on a slow connection the additional non-blocking bandwidth cost of its 10KB compressed download as expected. +* [ES Module Shims Polyfilling](bench/README.md#native-v-polyfill-performance) (for the remaining [28% of users](https://caniuse.com/import-maps)) is on average 1.4x - 1.5x slower than native module loading, and up to 1.8x slower on slow networks (most likely due to the browser preloader), both for cached and uncached loads, and this result scales linearly up to 10MB and 20k modules loaded executing on the fastest connection in just over 2 seconds in Firefox. * [Very large import maps](bench/README.md#large-import-maps-performance) (100s of entries) cost only a few extra milliseconds upfront for the additional loading cost. ## Features diff --git a/rollup.config.js b/rollup.config.js index a5c8ff57..5229831f 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -26,8 +26,6 @@ function config (isWasm) { resolveId (id) { if (isWasm && id === '../node_modules/es-module-lexer/dist/lexer.asm.js') return path.resolve('node_modules/es-module-lexer/dist/lexer.js'); - if (isWasm && id === './dynamic-import-csp.js') - return path.resolve('src/dynamic-import.js'); } }, replace({ diff --git a/src/dynamic-import-csp.js b/src/dynamic-import-csp.js deleted file mode 100644 index 813711df..00000000 --- a/src/dynamic-import-csp.js +++ /dev/null @@ -1,36 +0,0 @@ -import { createBlob, baseUrl, nonce } from './env.js'; - -let err; -window.addEventListener('error', _err => err = _err); -const inject = (s, errUrl) => new Promise((resolve, reject) => { - err = undefined; - s.ep = true; - if (nonce) - s.setAttribute('nonce', nonce); - - // Safari is unique in supporting module script error events - s.addEventListener('error', cb); - s.addEventListener('load', cb); - - function cb (_err) { - document.head.removeChild(s); - if (self._esmsi) { - resolve(self._esmsi, baseUrl); - self._esmsi = undefined; - } - else { - reject(!(_err instanceof Event) && _err || err && err.error || new Error(`Error loading or executing the graph of ${errUrl} (check the console for ${s.src}).`)); - err = undefined; - } - } - - document.head.appendChild(s); -}); - -export const dynamicImport = (url, opts) => inject(Object.assign(document.createElement('script'), { - type: 'module', - src: createBlob(`import*as m from'${url}';self._esmsi=m`) -}), opts && opts.errUrl || url); - -// This is done as a script so we don't trigger module loading too early for any loading import maps -export const supportsDynamicImportCheck = inject(Object.assign(document.createElement('script'), { src: createBlob('self._esmsi=u => import(u)') })).then(() => true, () => false); diff --git a/src/dynamic-import.js b/src/dynamic-import.js index c1ec6134..1d60daa5 100644 --- a/src/dynamic-import.js +++ b/src/dynamic-import.js @@ -1,44 +1,48 @@ -import { createBlob, baseUrl, hasDocument } from './env.js'; +import { createBlob, baseUrl, nonce, hasDocument } from './env.js'; -export let supportsDynamicImportCheck = false; +export let dynamicImport = !hasDocument && (0, eval)('u=>import(u)'); -// first check basic eval support -try { - eval(''); -} -catch (e) { - throw new Error(`The ES Module Shims Wasm build will not work without eval support. Either use the alternative CSP-compatible build or make sure to add both the "unsafe-eval" and "unsafe-wasm-eval" CSP policies.`); -} +export let supportsDynamicImport; -// polyfill dynamic import if not supported -export let dynamicImport; -try { - dynamicImport = (0, eval)('u=>import(u)'); - supportsDynamicImportCheck = true; -} -catch (e) {} - -if (hasDocument && !supportsDynamicImportCheck) { - let err; - window.addEventListener('error', _err => err = _err); - dynamicImport = (url, { errUrl = url }) => { - err = undefined; - const src = createBlob(`import*as m from'${url}';self._esmsi=m;`); - const s = Object.assign(document.createElement('script'), { type: 'module', src }); - s.setAttribute('noshim', ''); - document.head.appendChild(s); - return new Promise((resolve, reject) => { - s.addEventListener('load', () => { - document.head.removeChild(s); - if (self._esmsi) { - resolve(_esmsi, baseUrl); - _esmsi = null; - } - else { - reject(err.error || new Error(`Error loading or executing the graph of ${errUrl} (check the console for ${src}).`)); - err = undefined; +export const dynamicImportCheck = hasDocument && new Promise(resolve => { + const s = Object.assign(document.createElement('script'), { + src: createBlob('self._d=u=>import(u)'), + ep: true + }); + s.setAttribute('nonce', nonce); + s.addEventListener('load', () => { + if (!(supportsDynamicImport = !!(dynamicImport = self._d))) { + let err; + window.addEventListener('error', _err => err = _err); + dynamicImport = (url, opts) => new Promise((resolve, reject) => { + const s = Object.assign(document.createElement('script'), { + type: 'module', + src: createBlob(`import*as m from'${url}';self._esmsi=m`) + }); + err = undefined; + s.ep = true; + if (nonce) + s.setAttribute('nonce', nonce); + // Safari is unique in supporting module script error events + s.addEventListener('error', cb); + s.addEventListener('load', cb); + function cb (_err) { + document.head.removeChild(s); + if (self._esmsi) { + resolve(self._esmsi, baseUrl); + self._esmsi = undefined; + } + else { + reject(!(_err instanceof Event) && _err || err && err.error || new Error(`Error loading ${opts && opts.errUrl || url} (${s.src}).`)); + err = undefined; + } } + document.head.appendChild(s); }); - }); - }; -} + } + document.head.removeChild(s); + delete self._d; + resolve(); + }); + document.head.appendChild(s); +}); diff --git a/src/es-module-shims.js b/src/es-module-shims.js index 63ecb89f..0dff5bd7 100755 --- a/src/es-module-shims.js +++ b/src/es-module-shims.js @@ -28,9 +28,8 @@ import { importMapSrcOrLazy, setImportMapSrcOrLazy, } from './env.js'; -import { dynamicImport } from './dynamic-import-csp.js'; +import { dynamicImport, supportsDynamicImport } from './dynamic-import.js'; import { - supportsDynamicImport, supportsImportMeta, supportsImportMaps, supportsCssAssertions, diff --git a/src/features.js b/src/features.js index 94440d2a..aea97ea3 100644 --- a/src/features.js +++ b/src/features.js @@ -1,4 +1,4 @@ -import { dynamicImport, supportsDynamicImportCheck } from './dynamic-import-csp.js'; +import { dynamicImport, supportsDynamicImport, dynamicImportCheck } from './dynamic-import.js'; import { createBlob, noop, nonce, cssModulesEnabled, jsonModulesEnabled, hasDocument } from './env.js'; // support browsers without dynamic import support (eg Firefox 6x) @@ -7,51 +7,47 @@ export let supportsCssAssertions = false; export let supportsImportMaps = hasDocument && HTMLScriptElement.supports ? HTMLScriptElement.supports('importmap') : false; export let supportsImportMeta = supportsImportMaps; -export let supportsDynamicImport = false; -export const featureDetectionPromise = Promise.resolve(supportsImportMaps || supportsDynamicImportCheck).then(_supportsDynamicImport => { - if (!_supportsDynamicImport) - return; - supportsDynamicImport = true; +const importMetaCheck = 'import.meta'; +const cssModulesCheck = `import"x"assert{type:"css"}`; +const jsonModulesCheck = `import"x"assert{type:"json"}`; - if (!supportsImportMaps || cssModulesEnabled || jsonModulesEnabled) { - const importMetaCheck = 'import.meta'; - const cssModulesCheck = `import"x"assert{type:"css"}`; - const jsonModulesCheck = `import"x"assert{type:"json"}`; +export const featureDetectionPromise = Promise.resolve(dynamicImportCheck).then(() => { + if (!supportsDynamicImport || supportsImportMaps && !cssModulesEnabled && !jsonModulesEnabled) + return; - if (!hasDocument) - return Promise.all([ - supportsImportMaps || dynamicImport(createBlob(importMetaCheck)).then(() => supportsImportMeta = true, noop), - cssModulesEnabled && dynamicImport(createBlob(cssModulesCheck.replace('x', createBlob('', 'text/css')))).then(() => supportsCssAssertions = true, noop), - jsonModulesEnabled && dynamicImport(createBlob(jsonModulescheck.replace('x', createBlob('{}', 'text/json')))).then(() => supportsJsonAssertions = true, noop), - ]); + if (!hasDocument) + return Promise.all([ + supportsImportMaps || dynamicImport(createBlob(importMetaCheck)).then(() => supportsImportMeta = true, noop), + cssModulesEnabled && dynamicImport(createBlob(cssModulesCheck.replace('x', createBlob('', 'text/css')))).then(() => supportsCssAssertions = true, noop), + jsonModulesEnabled && dynamicImport(createBlob(jsonModulescheck.replace('x', createBlob('{}', 'text/json')))).then(() => supportsJsonAssertions = true, noop), + ]); - return new Promise(resolve => { - const iframe = document.createElement('iframe'); - iframe.style.display = 'none'; - iframe.setAttribute('nonce', nonce); - function cb ({ data: [a, b, c, d] }) { - supportsImportMaps = a; - supportsImportMeta = b; - supportsCssAssertions = c; - supportsJsonAssertions = d; - resolve(); - document.head.removeChild(iframe); - window.removeEventListener('message', cb, false); - } - window.addEventListener('message', cb, false); + return new Promise(resolve => { + const iframe = document.createElement('iframe'); + iframe.style.display = 'none'; + iframe.setAttribute('nonce', nonce); + function cb ({ data: [a, b, c, d] }) { + supportsImportMaps = a; + supportsImportMeta = b; + supportsCssAssertions = c; + supportsJsonAssertions = d; + resolve(); + document.head.removeChild(iframe); + window.removeEventListener('message', cb, false); + } + window.addEventListener('message', cb, false); - const importMapTest = `