Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RinatValiullov/004fabd752c864985ae61273969d3c3a to your computer and use it in GitHub Desktop.
Save RinatValiullov/004fabd752c864985ae61273969d3c3a 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment