Javascript - Module Loading Modules

Loading Modules with <script>

The <script> element loads JavaScript files as scripts by default.

It is equivalent to explicitly mentioning the type attribute with the content type as "text/javascript".

To support modules, the value module was added to type options. For example,

<script type="module" src="moduleFile.js"></script> 
<!-- load JavaScript file and recognize it as a module--> 

<script type="module"> 
<!?an inline module --> 

import { multiply } from "./moduleFile.js"; 
let result = multiply(1, 2); 
</script> 

Unlike scripts, modules use import to specify other files to be loaded for.

The module type for the script element always behaves as if the defer attribute was applied.

The defer attribute is optional for loading script files but is always applied for loading module files.

The module file starts getting downloaded as soon as the HTML parser encounters a <script type="module"> element.

So all modules are executed in the order in which they appear.

Related Topic