Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent ESModules from being deferred when imported with script tag

I've setup differential loading to serve ES6 modules to newer browsers. I've run into a problem where modules are deferred by default with the script tag even without the defer attribute. I.e.

<script type="module" src="..."></script>

is always deferred till all the HTML is parsed leading to a FOUC.

I've tried to prevent this and force parsing the file before the rest of the HTML is loaded by using

<script defer="false" type="module" src="..."></script>

<script defer="nodefer" type="module" src="..."></script>

<script async="false" type="module" src="..."></script>

None of these approaches seem to work. Whatever technique I use has to maintain differentiation between the ES6 and ES5 bundles. How do I prevent ESModules from being deferred till all the HTML is parsed even when included in the head?

like image 435
Avin Kavish Avatar asked Mar 13 '26 22:03

Avin Kavish


2 Answers

As seen here, you can't disable defer on module scripts:

Module scripts behave like defer by default – there's no way to make a module script block the HTML parser while it fetches.

However, to load ES6 modules in browser that support it and have ES5 modules available for backup, you can use nomodule as described here:

Older browsers won’t execute scripts with an unknown “type”, but you can define fallback scripts with the nomodule attribute:

<script type="module" src="module.js"></script>
<script nomodule src="fallback.js"></script>

If you're just worried about FOUC, hide your content until you're ready or ensure necessary CSS is inlined in the head.

like image 181
Ouroborus Avatar answered Mar 15 '26 10:03

Ouroborus


A module type script will execute immediately once parsed if it has the async keyword, for example:

<script type="module" async src="/static/.../component.min.js">

See This nice graph for a visual representation of what is happening:

like image 29
run_the_race Avatar answered Mar 15 '26 11:03

run_the_race



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!