I understand that you can detect features in javascript with something like this
if(xmlhttprequest){
console.log("this browser is ajax patible");
}
I also understand that ES6 imports are nativly patable with some browsers if certain dev mode settings are enabled. ie
import {someExport} from './someModule.js';
My question is
Is it possible to feature detect "Import" in the like you would an object? if yes, How can it be done? Is it possible to import whole JS file (so that an ES5 Javascript which does not use Export can be imported)
I have attempted using the if(object) syntax with various variations (including with and without a from statement) but so far have had no luck
My reason for this i I have build a javascript feature which relies on Jquery and GreenSock and want the script to import these automatically in patible browsers so the developer does not have to manually add multiple JS libraries.
I understand that you can detect features in javascript with something like this
if(xmlhttprequest){
console.log("this browser is ajax patible");
}
I also understand that ES6 imports are nativly patable with some browsers if certain dev mode settings are enabled. ie
import {someExport} from './someModule.js';
My question is
Is it possible to feature detect "Import" in the like you would an object? if yes, How can it be done? Is it possible to import whole JS file (so that an ES5 Javascript which does not use Export can be imported)
I have attempted using the if(object) syntax with various variations (including with and without a from statement) but so far have had no luck
My reason for this i I have build a javascript feature which relies on Jquery and GreenSock and want the script to import these automatically in patible browsers so the developer does not have to manually add multiple JS libraries.
Share Improve this question edited Dec 21, 2017 at 5:31 Cœur 38.7k26 gold badges203 silver badges277 bronze badges asked Jul 3, 2017 at 17:45 megamanmegaman 1,1012 gold badges14 silver badges25 bronze badges 1- See also How to feature-detect es6 modules (for exports) – Bergi Commented Aug 6, 2021 at 22:46
2 Answers
Reset to default 17It is safe to assume that all browsers that support ES6-style module import/export syntax can load modules through script tags using type="module"
. Those browsers also offer an attribute for script tags called nomodule
. You can therefore detect support from within JavaScript as follows:
'noModule' in HTMLScriptElement.prototype
(note the uppercase 'M' in the property name as opposed to the HTML attribute)
Have you considered using the nomodule attribute on script?
Example
<script type="module">
window.imports = true;
import './app-shell-es.js';
</script>
<script src="app-shell.js" nomodule></script>
Source: ECMAScript modules in browsers