I am not clearly understanding why the nomodule
attribute exists in the new browsers that support ES6 modules.
In HTML 5, the type
attribute is optional and defaults to text/javascript
:
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".
It doesn't default to <script type="module" src="module.js"></script>
. Has this default changed? If not, why would nomodule
be necessary? Can I just use <script src="bundle.js"></script>
without nomodule
?
nomodule attribute
The nomodule attribute is a boolean attribute which is used to indicate to a browser which does support modules that a certain script tag doesn't need to be loaded.
The purpose of the nomodule attribute is to have a backup script for older browser who don't support the
<script type="module">
and thus will ignore them. Because the older browser neither support the<script type="module">
nor the nomodule attribute the following scenarios can occur:Newer browsers, supports
<script type="module">
&<script nomodule type="text/javascript">
<script type="module">
script<script nomodule type="text/javascript">
.Older browsers, don't support
<script type="module">
&<script nomodule type="text/javascript">
<script type="module">
since its implementation cannot process this. No script will be downloaded and executed.<script nomodule type="text/javascript">
script.The purpose of the
nomodule
attribute is to cause newer browsers that support module scripts to ignore a particularscript
element:The spec has a good example:
So that’s how it works.
The default hasn’t changed—it’s still
text/javascript
. But thetype
attribute can now also have the valuemodule
, which means browsers still parse and execute it astext/javascript
—but also specifically as a module script.It’s necessary in order to prevent new browsers that support module scripts from executing a script that’s intended only for old browsers that don’t support module scripts, as in the above example.
Yes—if
bundle.js
doesn’t use modules. If it uses modules, you‘d want to puttype=module
on it (in which case old browsers will ignore it since they don’t recognize themodule
value fortype
).