-
-
Save ebidel/3201b36f59f26525eb606663f7b487d0 to your computer and use it in GitHub Desktop.
<!-- | |
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> |
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?
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
A more concise supportsStaticImport script:
function supportsStaticImport() {
return 'noModule' in HTMLScriptElement.prototype;
}
@erikt9 feel free to submit this as an answer to the Stackoverflow question linked above.
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');
}
@mindhells you feel also free to submit this as an answer to the Stackoverflow question linked above.
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).