简体   繁体   中英

JavaScript type module doesn't execute

I have below html file:

<!DOCTYPE html> 
<html lang="en"> 

<head> 

</head> 

<body> 

    <script type="module">
        console.log("test");
    </script>

</body>
</html>

However, the console doesn't print out anything. If I remove the type="module" , it works well. The version of Chrome I use is 58.0.3029.81. I also googled and tested my current Chrome supports ES6.

Any idea why?

It's not supported in version 58. https://caniuse.com/#search=type%3D%22module%22

But you can use nomodule to compatible with it.

The nomodule attribute is a boolean attribute that prevents a script from being executed in user agents that support module scripts. This allows selective execution of module scripts in modern user agents and classic scripts in older user agents, as shown below. The nomodule attribute must not be specified on module scripts (and will be ignored if it is).

Here's a html.spec.whatwg.org 's example

This example shows how to include a module script for modern user agents, and a classic script for older user agents:

<script type="module" src="app.mjs"></script>
<script nomodule defer 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 a type of "module" will be fetched and evaluated (as a module script). Conversely, older user agents will ignore the script element with a type of "module", as that is an unknown script type for them — but they will have no problem fetching and evaluating the other script element (as a classic script), since they do not implement the nomodule attribute.

It means in higher than version 61 type=module and nomodule is supported, then:

  1. The script will be executed in script element with type of "module".
  2. The script will be not executed in script element with attribute of "nomodule".

And in lower than version 60 type=module and nomodule isn't supported, then:

  1. The script will be not executed in script element with type of "module", because type=module is an unknown script type for the browser.
  2. The script will be executed in script element with attribute of "nomodule", because the browser doesn't implement the "nomodule" attribute.

Hope that can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM