What is the purpose of the HTML "nomodule" attribute for script elements if text / javascript is used by default?

I don’t understand why the nomodule attribute exists in new browsers that support ES6 modules.

In HTML 5, the type attribute is optional and the default is text/javascript :

The type attribute provides a script language or data format. If an attribute is present, its value must be a valid MIME type. The charset parameter is not specified. The default value, which is used if the attribute is absent, is "text / javascript".

It does not have a default value <script type="module" src="module.js"></script> . Is this default value changed? If not, then why use a nomodule ? Can I use <script src="bundle.js"></script> without a nomodule ?

+5
source share
1 answer

The purpose of the nomodule attribute is to call newer browsers that support module scripts in order to ignore a single script element:

The nomodule attribute is a boolean attribute that prevents script execution in user agents that support module scripts.

The spectrum has a good example :

This example shows how to enable the script module for modern user agents and the classic script for older user agents:

 <script type="module" src="app.js"></script> <script nomodule src="classic-app-bundle.js"></script> 

In modern user agents that support module scripts, the script element with the nomodule attribute will be ignored, and the script element with the type " module " will be retrieved and evaluated (as a script module). Conversely, old user agents will ignore the script element with the type β€œ module ” because they have an unknown script type, but they will not have problems retrieving and evaluating another script element (like a classic script), since they do not implement the nomodule attribute.

So how does it work.

In HTML 5, the type attribute is optional and defaults to text/javascript ... Is this the default value changed?

The default value has not changed - its still text/javascript . But the type attribute can now also have the value module , which means that browsers still parse and execute it as text/javascript , but also specifically as a script module.

If not, why do you need a nomodule ?

This is necessary to prevent the appearance of new browsers that support the execution of scripts of the script module, intended only for older browsers that do not support scripts of modules, as in the above example.

Can I use <script src="bundle.js"></script> without a nomodule ?

Yes, if bundle.js does not use modules. If it uses modules, you want to put type=module on it (in this case, old browsers will ignore it, because they do not recognize the value of module for type ).

+11
source

Source: https://habr.com/ru/post/1271339/


All Articles