Hacker News new | past | comments | ask | show | jobs | submit login

Why is type="module" the opposite of nomodule? This isn't a real question... just a big ol sigh



It’s a way of conveniently achieving compatibility with old and new browsers.

JavaScript is executed differently when it’s a “module script” to when it’s a “classic script” (using the HTML spec terms), so you want a way of preventing old browsers from executing it (whether they’re syntactically compatible or not). Hence type="module", because old browsers won’t execute scripts with the type attribute containing an unknown value.

Once you have that, you commonly want to bifurcate on modules support, so you want a way of saying “don’t execute this if you support modules”. This can be done with feature-detection code, to the effect of “does it support modules? if yes, do nothing; if no, load the code, probably by adding another script tag with the correct src to the document”, but this is inconvenient and causes at least mild inconvenience with security measures like Content-Security-Policy. So the solution was to put another attribute there that new browsers could use as the inverse of type="module": nomodule.

Perhaps it’s a big ol’ sigh, but as is very commonly the case with such sighs, they make a good deal of sense when you understand the reasons and history involved.


Be really interesting to understand when this actually get's executed

  <script type="module">
    document.documentElement.classList.remove('no-js');
    document.documentElement.classList.add('js');
  </script>
module has defer semantics by default i.e. it gets executed after the document has finished parsed, and I can't find anything in the WHATWG spec to suggest it's different for inline scripts

Maybe inline scripts ignore module, as they do defer and async


Inline <script type="module"> is executed after DOMContentLoaded.

Inline <script> is executed during parsing.

https://html.spec.whatwg.org/multipage/scripting.html#the-sc... gives the full details of the interactions between type, src, defer and async. Inline scripts are normally referred to as script elements where the src attribute is not present.


Wow, thanks for that detail. That's some obscura to me.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: