Today I Learned : ES modules in browser

All you need is type=module on the script element, and the browser will treat the inline or external script as an ECMAScript module. I am sharing some few browser-specific things I'd learned while getting my hands dirty.

With regular scripts you can use defer to prevent blocking, which also delays script execution until the document has finished parsing, and maintains execution order with other deferred scripts. Module scripts use the same execution queue as regular scripts using defer. This is applicable to both inline and src scripts. There is no way to block the HTML parser when using a module script.

As with regular scripts, async causes the script to download without blocking the HTML parser and executes as soon as possible. Unlike regular scripts, async also works on inline modules.

As always with async, scripts may not execute in the order they appear in the DOM.

If you understand ES modules, you'll know you can import them multiple times but they'll only execute once. Well, the same applies to script modules in HTML – a module script of a particular URL will only execute once per page.

Unlike regular scripts, module scripts (and their imports) are fetched with CORS. This means cross-origin module scripts must return valid CORS headers such as Access-Control-Allow-Origin: *.

blogs