33

What is the difference between loading JavaScript files in HTML using <script type=text/javascript> and <script type=module>?

3

1 Answer 1

27

The HTML5 specification discourages the use of type=text/javascript:

From https://www.w3.org/TR/html5/semantics-scripting.html#element-attrdef-script-type:

Omitting the (type) attribute, or setting it to a JavaScript MIME type, means that the script is a classic script, to be interpreted according to the JavaScript Script top-level production. Classic scripts are affected by the charset, async, and defer attributes. Authors should omit the attribute, instead of redundantly giving a JavaScript MIME type.

Setting the attribute to an ASCII case-insensitive match for the string "module" means that the script is a module script, to be interpreted according to the JavaScript Module top-level production. Module scripts are not affected by the charset and defer attributes.

(emphasis by me)

4
  • 6
    In addition to "Andrian W" answer, if we set script type module,we can import other JavaScript modules inside this script like <script type=module> import {sum} from "./arithmetic" </script> Commented Jul 20, 2018 at 8:23
  • 6
    Also variables in a script type module are by default scoped to that script block and not global as with normal script blocks. You can still define global variables by explicitly declaring them under the window object.
    – Kolya
    Commented Aug 5, 2020 at 12:34
  • And Modules work only via HTTP(s), not locally Commented Jul 28 at 13:16
  • In the browser, import must get either a relative or absolute URL. Modules without any path are called “bare” modules. Such modules are not allowed in import. see: javascript.info/modules-intro Commented Jul 28 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.