Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect ES6 import compatibility

I understand that you can detect features in javascript with something like this

if(xmlhttprequest){
console.log("this browser is ajax compatible");
}

I also understand that ES6 imports are nativly compatable 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 compatible browsers so the developer does not have to manually add multiple JS libraries.

like image 259
megaman Avatar asked Dec 10 '22 10:12

megaman


1 Answers

It 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)

like image 99
Cref Avatar answered Dec 28 '22 06:12

Cref