Skip to content

Instantly share code, notes, and snippets.

@ebidel
Last active September 4, 2023 13:56
  • Star 52 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ebidel/3201b36f59f26525eb606663f7b487d0 to your computer and use it in GitHub Desktop.
Feature detect ES modules: both static import and dynamic import()
<!--
Complete feature detection for ES modules. Covers:
1. Static import: import * from './foo.js';
2. Dynamic import(): import('./foo.js').then(module => {...});
Demo: http://jsbin.com/tilisaledu/1/edit?html,output
Thanks to @_gsathya, @kevincennis, @rauschma, @malyw for the help.
-->
<body></body>
<!-- Remember: static modules have a fallback! -->
<script type="module">
console.log('This browser supports <script type="module">');
</script>
<script nomodule>
console.log('This browser DOES NOT support <script type="module">');
</script>
<script>
// Feature detect static imports.
function supportsStaticImport() {
const script = document.createElement('script');
return 'noModule' in script;
}
// Feature detect dynamic import().
function supportsDynamicImport() {
try {
new Function('import("")');
return true;
} catch (err) {
return false;
}
}
// Usage.
let el = document.createElement('pre');
el.textContent = `
Supports ES module static import: ${supportsStaticImport()}
Supports dynamic ES module import(): ${supportsDynamicImport()}
`
document.body.appendChild(el);
</script>
@jcdalton2201
Copy link

@ebidel what is a good polyfill for dynamic import?

@derappelt
Copy link

@xeaone
Copy link

xeaone commented Sep 23, 2019

@ebidel

The use of new Function creates a new function but does not invoke this new function. I am pretty sure the current supportsDynamicImport() always returns true. The fix for this issue would need to add () after new Function.

This would NOT execute.

new Function('import("")');

This would execute.

new Function('import("")')();

I would also suggest catching the uncaught promise error. So line 32 could look as follows.

new Function('import("").catch(function(){})')();

@KevinBrogan
Copy link

@vokeio You don't want to execute the import, you just want to check that it is valid syntax. "new Function()" will throw on invalid syntax.

@xeaone
Copy link

xeaone commented Dec 2, 2019

@KevinBrogan if you give it a test in the browsers you will see the new Function does not execute. You could put any thing in there and it will not execute. Copy and paste the try catch in the browser console replace the import with fooBar or anything else you would like and you will see what I mean. It will always console log true. Unless I am missing something...

try {
	new Function('fooBar()');
	console.log(true);
} catch (err) {
	console.log(false);
}

@KevinBrogan
Copy link

I think what you are missing, is that import and import() are both reserved keyword syntax errors on older browsers. fooBar() and import() are not both functions calls. One is a function call to a possibly defined external symbol, the other is a syntax error.

new Function('import("")');

This will compile on browsers that support it, and it will fail to compile and error on browsers that do not support it.


new Function('import("")')();

This will error on all browsers. Supporting browsers will complain about an invalid import after successfully compiling the script and then executing it, while non supporting browsers will complain about a syntax error on the compile step.


IE 11 screenshot:

image

@mhofman
Copy link

mhofman commented Jan 30, 2020

The dynamic import detection relies on a form of eval, which will be blocked by unsafe-eval CSP. While there may be workarounds (e.g. blob, nonce, etc), these would only be practical for a Web App, not a library.

Does anyone have an idea how a "loader" type library can feature detect dynamic import so it could dynamically load an ES Module implementation, without assuming anything from the embedding app (no requirement for bundler transforms, CSP changes, etc).

@rugk
Copy link

rugk commented Feb 20, 2020

Does anyone have an idea how a "loader" type library can feature detect dynamic import so it could dynamically load an ES Module implementation, without assuming anything from the embedding app (no requirement for bundler transforms, CSP changes, etc).

A perfect case for Stackoverflow, I've asked it there: How to feature-detect whether a browser supports dynamic ES6 module loading?

@Mouvedia
Copy link

Mouvedia commented Feb 3, 2021

console.log('This browser DOES NOT support <script type="module">');

This is wrong.
e.g. Safari 10.1 supports type="module" but not the nomodule attribute
see https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc

@erikt9
Copy link

erikt9 commented Dec 7, 2021

A more concise supportsStaticImport script:

function supportsStaticImport() {
    return 'noModule' in HTMLScriptElement.prototype;
}

@rugk
Copy link

rugk commented Dec 8, 2021

@erikt9 feel free to submit this as an answer to the Stackoverflow question linked above.

@mindhells
Copy link

https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement

function checkModuleSupport() {
  if ('supports' in HTMLScriptElement) {
    return HTMLScriptElement.supports('module');
  }
  return 'noModule' in document.createElement('script');
}

@rugk
Copy link

rugk commented Mar 18, 2022

@mindhells you feel also free to submit this as an answer to the Stackoverflow question linked above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment