Sub topic 6
Running Modules in the Browser
This chapter assumes you know the import and export forms from earlier chapters. You should also understand what a module specifier is: a relative path, an absolute URL, or a bare name. You need a terminal and a modern browser to follow along. The chapter covers how the browser finds, fetches, and runs module files, and how import maps let you use bare names without a bundler.
Declaring a Module Script
A browser treats a script as a classic script unless you tell it otherwise. Adding type="module" to the <script> element makes the browser parse the code as an ES module. Without that attribute, any import or export statement is a syntax error.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Modules demo</title>
<script type="module" src="./main.js"></script>
</head>
<body>
<p id="out"></p>
</body>
</html>// main.js
import { area } from './math.js';
document.querySelector('#out').textContent = `Area: ${area(3)}`;// math.js
export const PI = 3.14159;
export function area(radius) {
return PI * radius * radius;
}The module script sits in <head> and still finds the <p> element. Module scripts are deferred by default, so they run after the HTML is fully parsed. You do not need a defer attribute or a DOMContentLoaded listener.
How module scripts differ from classic scripts
| Behavior | Classic `<script>` | `<script type="module">` |
|---|---|---|
| Parse timing | Blocks HTML parsing unless `defer` or `async` | Deferred by default |
| Strict mode | Only with `"use strict"` | Always strict |
| Top-level `var` and functions | Become properties of `window` | Stay in module scope |
| Top-level `this` | `window` | `undefined` |
| Cross-origin fetch | No CORS check | Requires CORS headers |
| Same `src` included twice | Runs twice | Runs once |
| `import` / `export` | Syntax error | Allowed |
The "runs once" row matters. The browser keeps a module map keyed by the resolved URL. If two scripts or two modules import ./math.js, the browser fetches and evaluates it once, and every importer shares the same instance.
Serving Files over HTTP
If you open index.html straight from disk with a file:// URL, the module will not load. The console shows a CORS error. Module scripts are fetched in CORS mode, and browsers do not treat file:// as a valid origin for that check.
Serve the folder with any local web server instead:
python3 -m http.server 8000Then open http://localhost:8000/. Any static server works, as long as it sends JavaScript files with a JavaScript MIME type such as text/javascript.
How the Browser Loads a Module Graph
The browser starts at the entry script and builds the whole dependency graph before it runs any code. It fetches main.js, parses it, finds the static import declarations, resolves each specifier against the importing module's URL, and fetches those files. It repeats this until every module in the graph is loaded. Evaluation happens only after that, with dependencies running before the modules that import them.
A deep import chain becomes a waterfall: the browser only learns about c.js after it has parsed b.js. You can tell the browser about modules ahead of time with modulepreload:
<link rel="modulepreload" href="./math.js">This fetches and parses the module early and puts it in the module map, so the later import finds it already loaded.
The async attribute
Adding async to a module script makes it run as soon as its graph is ready, without waiting for the HTML parse to finish or for other scripts. Use it for independent code such as analytics, where order does not matter.
<script type="module" async src="./analytics.js"></script>Inline module scripts
A module script can be inline. Relative specifiers inside it resolve against the page's URL.
<script type="module">
import { area } from './math.js';
console.log(area(2));
</script>Inline modules are deferred as well. Each one has its own module scope, so a const declared in one inline module is not visible in another.
Specifier Rules in the Browser
The browser resolves specifiers as URLs. Without help, it accepts only these forms:
- Relative:
./math.js,../lib/math.js - Root-relative:
/src/math.js - Absolute URL:
https://cdn.example.com/lib.js
There is no automatic extension lookup and no index.js lookup. import './math' requests the URL /math, which usually returns a 404. A bare specifier such as import debounce from 'lodash-es' throws a TypeError saying the specifier was not remapped to a URL. Import maps fix this.
Import Maps
An import map is a JSON object in a <script type="importmap"> element. It tells the browser how to turn specifiers into URLs. Put it before any module script that depends on it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Import map demo</title>
<script type="importmap">
{
"imports": {
"geometry": "/src/math.js",
"lodash-es/": "/vendor/lodash-es/"
}
}
</script>
<script type="module" src="./app.js"></script>
</head>
<body></body>
</html>// app.js
import { area } from 'geometry';
import debounce from 'lodash-es/debounce.js';
const logArea = debounce(() => console.log(area(3)), 200);
window.addEventListener('resize', logArea);The map uses two kinds of keys:
- An exact key such as
"geometry"matches only that specifier. - A key ending in
/such as"lodash-es/"is a prefix match.lodash-es/debounce.jsbecomes/vendor/lodash-es/debounce.js. The value must also end in/.
The map applies to every module on the page, including modules loaded through import(), so app.js and its own dependencies all see the same mappings.
Scoped mappings
The scopes field overrides mappings for modules whose URL starts with a given prefix. You can use it to give one part of the code a different version of a dependency:
{
"imports": {
"lodash-es/": "/vendor/[email protected]/"
},
"scopes": {
"/legacy/": {
"lodash-es/": "/vendor/[email protected]/"
}
}
}A module at /legacy/report.js that imports lodash-es/debounce.js gets version 4.17.15. Every other module gets 4.17.21.
Fallback for Old Browsers
Browsers that predate modules ignore type="module". They do run scripts marked nomodule, which module-aware browsers skip. You can pair a modern entry with a bundled legacy build:
<script type="module" src="./main.js"></script>
<script nomodule src="./legacy-bundle.js"></script>Every current major browser supports modules, so most projects now skip this pattern unless analytics show real traffic from very old clients.
Common Errors and What They Mean
| Symptom | Cause | Fix |
|---|---|---|
| `Cannot use import statement outside a module` | Missing `type="module"` | Add the attribute |
| CORS error when opening the page | Loaded from `file://` | Serve over HTTP |
| MIME type error | Server sends the wrong `Content-Type` | Configure the server |
| `Failed to resolve module specifier "x"` | Bare specifier with no mapping | Add an import map entry |
| 404 for `/math` | Extension omitted | Write `./math.js` |
| Code runs once, not twice | Module map caches by URL | Expected behavior |
Exercise
A page includes <script type="module" src="./a.js"></script> twice, and a.js contains console.log('loaded'). How many times is "loaded" printed, and why?
Show answer
Once. The browser caches module instances in its module map by resolved URL, so the second script finds ./a.js already evaluated and does not run it again.
Exercise
With the import map {"imports": {"utils/": "/lib/utils/"}}, what URL does import { slug } from 'utils/string.js' request, and what happens with import { slug } from 'utils'?
Show answer
utils/string.js matches the prefix key utils/ and resolves to /lib/utils/string.js. The bare utils does not match the prefix key, because prefix keys only match specifiers that continue past the slash, so resolution fails with a TypeError. Add an exact "utils" key to support it.
Exercise
A module script in <head> runs document.querySelector('#out').textContent = 'hi' and works, but the same code in a classic script in <head> throws. Explain the difference.
Show answer
Module scripts are deferred by default and run after the HTML is parsed, so #out exists. A classic script in <head> runs immediately, before the <p id="out"> element has been parsed, so querySelector returns null and setting textContent throws a TypeError.