Browser Modules
Modern web browsers natively support ES6 modules! However, there are a few important rules to be aware of when importing JavaScript directly into an HTML file.
The type="module" Attribute
If you include a standard <script> tag in your HTML, the browser will execute it as a standard, legacy script. Standard scripts are executed immediately, halting HTML parsing, and they pollute the global namespace.
To tell the browser that the file contains modern import/export syntax, you must add the type="module" attribute to the script tag.
<!-- Legacy Scripts -->
<script src="legacyScript.js"></script>
<!-- Modern ES6 Modules -->
<script type="module" src="modernModule.js"></script>
Advantages of Browser Modules
Using type="module" provides several massive advantages over legacy scripts:
- Isolation: Variables and functions defined inside a module are heavily isolated. They do not pollute the global
windowobject. To be accessed externally, they must be explicitly exported. - Deferred Execution: Modules are automatically deferred by default. The browser will wait for the entire HTML document to finish parsing before executing the module, ensuring you don’t get null errors when trying to select DOM elements.
- Strict Mode: ES6 modules inherently run in Strict Mode.