Skip to content

Commit

Permalink
feat: direct dynamic import (#327)
Browse files Browse the repository at this point in the history
  • Loading branch information
guybedford authored Aug 15, 2022
1 parent c85fe26 commit f6f6ba4
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 126 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -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
Expand Down
2 changes: 0 additions & 2 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
36 changes: 0 additions & 36 deletions src/dynamic-import-csp.js

This file was deleted.

82 changes: 43 additions & 39 deletions src/dynamic-import.js
Original file line number Diff line number Diff line change
@@ -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);
});
3 changes: 1 addition & 2 deletions src/es-module-shims.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
82 changes: 39 additions & 43 deletions src/features.js
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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 = `<script nonce=${nonce}>const b=(s,type='text/javascript')=>URL.createObjectURL(new Blob([s],{type}));document.head.appendChild(Object.assign(document.createElement('script'),{type:'importmap',nonce:"${nonce}",innerText:\`{"imports":{"x":"\${b('')}"}}\`}));Promise.all([${
supportsImportMaps ? 'true,true' : `'x',b('${importMetaCheck}')`}, ${cssModulesEnabled ? `b('${cssModulesCheck}'.replace('x',b('','text/css')))` : 'false'}, ${
jsonModulesEnabled ? `b('${jsonModulesCheck}'.replace('x',b('{}','text/json')))` : 'false'}].map(x =>typeof x==='string'?import(x).then(x =>!!x,()=>false):x)).then(a=>parent.postMessage(a,'*'))<${''}/script>`;
// setting srcdoc is not supported in React native webviews on iOS
// setting src to a blob URL results in a navigation event in webviews
// document.write gives usability warnings
if ('srcdoc' in iframe)
iframe.srcdoc = importMapTest;
else
iframe.contentDocument.write(importMapTest);
document.head.appendChild(iframe);
});
}
const importMapTest = `<script nonce=${nonce}>const b=(s,type='text/javascript')=>URL.createObjectURL(new Blob([s],{type}));document.head.appendChild(Object.assign(document.createElement('script'),{type:'importmap',nonce:"${nonce}",innerText:\`{"imports":{"x":"\${b('')}"}}\`}));Promise.all([${
supportsImportMaps ? 'true,true' : `'x',b('${importMetaCheck}')`}, ${cssModulesEnabled ? `b('${cssModulesCheck}'.replace('x',b('','text/css')))` : 'false'}, ${
jsonModulesEnabled ? `b('${jsonModulesCheck}'.replace('x',b('{}','text/json')))` : 'false'}].map(x =>typeof x==='string'?import(x).then(x =>!!x,()=>false):x)).then(a=>parent.postMessage(a,'*'))<${''}/script>`;
// setting srcdoc is not supported in React native webviews on iOS
// setting src to a blob URL results in a navigation event in webviews
// document.write gives usability warnings
if ('srcdoc' in iframe)
iframe.srcdoc = importMapTest;
else
iframe.contentDocument.write(importMapTest);
document.head.appendChild(iframe);
});
});

0 comments on commit f6f6ba4

Please sign in to comment.