What is the difference between loading JavaScript files in HTML using <script type=text/javascript>
and <script type=module>
?
1 Answer
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)
-
6In 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
-
6Also 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.– KolyaCommented Aug 5, 2020 at 12:34
-
-
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
type="module"
, you can import modules into your code.type="text/javascript"
is outdated.