TaskAdd a single <script type='module'> block to the page that logs 'module ready' to the console. The page should be a complete HTML5 document.
<script type='module'>: ES modules in the browser
75 XP6 min
Theory
Two kinds of <script>
<script src="app.js"></script> <!-- classic script --> <script type="module" src="app.js"></script> <!-- ES module -->
Browsers have shipped ES modules since 2017. type="module" flips three things:
- import / export work β without it,
importis a syntax error. - Strict mode is on β implicit globals throw,
thisat top level isundefined. - Deferred by default β module scripts wait until the DOM is parsed before running, like classic
defer. No more "put the script at the end of body."
The smallest possible example
<script type="module">
console.log("running as a module");
// import { something } from "./other.js"; // works here, would error in a classic script
</script>Same syntax inline OR in an external file. The type="module" attribute is what matters.
What you give up with type="module"
<script>alert(typeof window === "object")</script> <!-- "object" --> <script type="module">alert(typeof window === "object")</script> <!-- "object" (window is still global) -->
The window is still global. What you lose:
- `this` at top level β in classic scripts
thisiswindow; in modules it'sundefined. Production code rarely relies on this anyway. - Implicit globals β
x = 5withoutletthrows in module strict mode. Good. - CORS β modules loaded from a file:// URL won't work; you need an HTTP server.
π
Sign up to start coding
Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β card required, cancel anytime.
Sign up β free trial βFirst 10 lessons in each track are free. No card needed for those.