35

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

3
  • 5
    With type="module", you can import modules into your code. Commented Jul 19, 2018 at 9:27
  • 2
    type="text/javascript" is outdated. Commented Jul 19, 2018 at 9:27
  • 4
    See developer.mozilla.org/en-US/docs/Web/HTML/Element/script Commented Jul 19, 2018 at 9:28

1 Answer 1

28

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)

Sign up to request clarification or add additional context in comments.

4 Comments

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>
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.
And Modules work only via HTTP(s), not locally
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

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.