Using JavaScript modules in browsers 2:Using JS modules in browsers

In web applications, you can set the type attribute of the<script>tag to module, so that the browser will recognize the introduced script as a JS module.

The browser recognizes the typ=”module” attribute and ignores scripts with the nomodule attribute set. This means that you can provide JS module based code to browsers that support module loading, while causing browsers that do not support module loading to fall back to normal JavaScript script mode.

If in terms of performance, this ability to distinguish scripts is surprisingly useful.

Think about it: Only modern browsers support modules. If a browser can recognize your module code, it must also support new JavaScript features before the modularity standard, such as arrow functions and async await.

You don’t need to compile code written with new features anymore! Can provide modern browsers with smaller, largely non recompiled code. Only browsers that do not support module loading will request scripts to set the nomodule.

The difference between JS modules and regular JavaScript scripts specific to browser environments

As mentioned earlier, JS module loading is different from regular JS loading.

We have listed some platform agnostic differences above, and they also have some differences in the browser environment.

As mentioned earlier, JS module loading is different from regular JS loading.

We have listed some platform agnostic differences above, and they also have some differences in the browser environment.

For example, a JS module will only be parsed and executed once by the browser, while a regular JS script will parse and execute it every time it is introduced through<script>.

Moreover, JS module scripts and dependencies have cross domain limitations, which means that any cross domain JS module script must have the correct HTTP header information. For example: Access Control Allow Origin: *. And regular JavaScript scripts do not have these limitations.

Another difference is related to the async attribute, which can prevent the download of JavaScript scripts from blocking HTML parsing (like defer), but at the same time, the async attribute also causes the script to execute immediately after loading (defer is executed after HTML parsing is completed), which cannot guarantee the execution order of the script and does not wait for HTML parsing to complete.

The async attribute does not take effect in inline regular JavaScript scripts, but it can take effect in inline JS module mode.