I was going through the WHATWG specifications for async
and defer
attributes for the <script>
tag, when I saw this statement:
Classic scripts may specify
defer
orasync
; module scripts may specifyasync
.
I went through the WHATWG definitions for classic and module scripts, but I didn't really get much clarity. In simple terms, what are the differences between classic and module scripts in JavaScript?
Module Script has its Own Scope The scope of variables, functions etc in a <script type="module"> tag is limited to that block. In a normal <script> tag variables, functions etc have global scope. These are available even inside module script tags.
A module script is one that contains an ES6 module, i.e. it uses (or: can use) import and export declarations. From §8.1.3.8 Integration with the JavaScript module system: The JavaScript specification defines a syntax for modules, as well as some host-agnostic parts of their processing model.
1) Maintainability: By definition, a module is self-contained. A well-designed module aims to lessen the dependencies on parts of the codebase as much as possible, so that it can grow and improve independently. Updating a single module is much easier when the module is decoupled from other pieces of code.
A script tag having type="module" attribute specifies that it to be considered as a Javascript module. It may be importing other Javascript module(s) inside it and becomes a "top-level" module for the imported modules.
The difference between the module script and the classic script is summarized at the Classic scripts v/s module scripts in Javascript Stack Overflow Answer . Quoting: Modules are singleton.
The main difference is that @JsModule always loads the script as the module script, while @JavaScript loads the script either as the module script (if the path to script is prefixed with ./ - then the script will be loaded from the frontend/ folder), or as a classic script (if loading from the external URL such as https:// ).
The module type serves roughly the same purpose as the type="module" attribute does for a script tag. It tells the browser the worker script being loaded is an ES6 module (which is necessary meta data to know how to parse and run it, as this article goes into a bit ).
The only way to load a script as a classic script is to place the javascript file into e.g. src/main/webapp/js/test.js and call Page.addJavaScript ("context://js/test.js"). You can use both @JsModule and @JavaScript to load script as a module script.
Here are the differences I have noted from various articles. If you want more details, read a complete article on the web:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With