ES modules have a loading graph
Follow one shared module through live bindings, measured HTTP loading, initialization failures and URL identity using a complete native-button example.

If you can already attach a click handler and split a function into another file, ES modules introduce a useful next question: which files must finish initializing before this handler can exist? An import describes a dependency. It also establishes a binding to another module’s exports, with a lifetime that can outlast an individual view.
This example uses ordinary browser modules over HTTP, without a bundler. Two files import one counter. We will distinguish its changing value from a copied number, measure the loading graph, and break specific stages deliberately. The MDN modules guide supplies the broader language and browser context.
One counter, two importers
Save these three files inside a modules directory. identity is a frozen, empty object used only as a reference token. Freezing it does not freeze the separately exported count binding.
// modules/counter.mjs
export let count = 0;
export const identity = Object.freeze({});
console.info("evaluate counter.mjs");
export function increment() {
count += 1;
}
// modules/view.mjs
import { count, identity } from "./counter.mjs";
const initialCount = count;
export const viewIdentity = identity;
console.info("evaluate view.mjs");
export function mountView(root) {
const live = root.querySelector("#live-count");
const initial = root.querySelector("#initial-count");
function render() {
live.textContent = String(count);
initial.textContent = String(initialCount);
}
render();
return { render };
}
count is a live imported binding. Each call to render() reads its current value. By contrast, initialCount receives a number once, during view.mjs evaluation. Calling the renderer again does not repeat that declaration. The import reference distinguishes these read-only imported bindings from mutable objects an export might reference. An importer cannot assign count = 9; the counter module can change its own binding through increment().
The arrows mean “depends on,” not “fetch another independent store.” For this acyclic graph, counter evaluation precedes view evaluation, which precedes the entry’s handler setup. Request completion order is a different observation.
Mount a small, inspectable interface
The entry connects the native buttons and publishes readiness only after its dependencies have evaluated. Its second action makes the URL-identity comparison explicit. Keep these files on a disposable local test origin.
// modules/main.mjs
import { identity, increment } from "./counter.mjs";
import { mountView, viewIdentity } from "./view.mjs";
console.info("evaluate main.mjs");
const root = document.querySelector("#module-demo");
const button = root.querySelector("#increment-count");
const compare = root.querySelector("#compare-urls");
const result = root.querySelector("#url-result");
const view = mountView(root);
let active = true;
let comparing = false;
root.querySelector("#shared-identity").textContent = identity === viewIdentity
? root.dataset.same : root.dataset.different;
function activate() {
increment();
view.render();
}
async function compareURLs() {
if (!active || comparing) return;
comparing = true;
compare.setAttribute("aria-busy", "true");
try {
const [shared, again, separate] = await Promise.all([
import("./counter.mjs"), import("./counter.mjs"),
import("./counter.mjs?copy=1")
]);
if (!active) return;
const originalBefore = shared.count;
const separateBefore = separate.count;
separate.increment();
result.textContent = [
`${root.dataset.namespace}: ${shared === again}`,
`${root.dataset.identity}: ${shared.identity === separate.identity}`,
`${root.dataset.original}: ${originalBefore} → ${shared.count}`,
`${root.dataset.copy}: ${separateBefore} → ${separate.count}`
].join("\n");
} catch (error) {
if (active) result.textContent = `${root.dataset.failed}: ${error.name}`;
} finally {
comparing = false;
compare.removeAttribute("aria-busy");
}
}
button.addEventListener("click", activate);
compare.addEventListener("click", compareURLs);
button.disabled = compare.disabled = false;
root.querySelector("#module-state").textContent = root.dataset.ready;
export function dispose() {
active = false;
button.removeEventListener("click", activate);
compare.removeEventListener("click", compareURLs);
button.disabled = compare.disabled = true;
root.querySelector("#module-state").textContent = root.dataset.stopped;
}
Save the following page as demo/index.html, with demo.css at the server root. Absolute entry and stylesheet paths are intentional; imports inside /modules/main.mjs resolve relative to that module’s URL. Moving the HTML page into a deeper directory does not move ./counter.mjs into that directory.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>One shared module, two readers</title>
<link rel="stylesheet" href="/demo.css">
<script type="module" src="/modules/main.mjs"></script>
</head>
<body>
<section id="module-demo" aria-labelledby="demo-title"
data-namespace="Same URL: same namespace"
data-identity="Original and query copy: same identity"
data-original="Original count"
data-copy="Query-copy count"
data-failed="Comparison failed"
data-same="Both importers share one identity."
data-different="Different module identities."
data-ready="Module graph evaluated; the button is ready."
data-stopped="Stopped. Reload to mount a new view.">
<h1 id="demo-title">One shared module, two readers</h1>
<p>The entry and view import the same counter URL. The view reads its live count again after each activation.</p>
<button id="increment-count" type="button" disabled>Increase by one</button>
<p>Live count: <output id="live-count">—</output></p>
<p>Value copied when view.mjs evaluated: <output id="initial-count">—</output></p>
<p id="shared-identity">Identity not checked yet.</p>
<p id="module-state">Waiting for the module graph. A load error leaves this button disabled.</p>
<section id="url-panel" aria-labelledby="url-title">
<h2 id="url-title">Compare resolved URLs</h2>
<p>This action imports counter.mjs again and imports counter.mjs?copy=1, then increments only the query copy.</p>
<button id="compare-urls" type="button" disabled>Compare module URLs</button>
<pre id="url-result" role="status">No comparison yet.</pre>
</section>
</section>
</body>
</html>
/* demo.css */
* { box-sizing: border-box; }
body { margin: 1rem; font: 1rem/1.6 system-ui, sans-serif; }
#module-demo { max-inline-size: 40rem; overflow-wrap: anywhere; }
button { font: inherit; max-inline-size: 100%; white-space: normal; }
output { font-weight: 700; }
:focus-visible { outline: 3px solid #315b32; outline-offset: 3px; }
pre { font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }
#url-panel { border-block-start: 1px solid #777; margin-block-start: 2rem; }
Serve the directory containing modules, demo, and demo.css, for example with python3 -m http.server 8080, then open /demo/index.html. Check that module responses have a JavaScript MIME type. The .mjs suffix alone cannot repair a server that returns an HTML fallback. A direct file: opening also does not reproduce this HTTP setup.
The script element reference explains why this ordinary module entry needs no added defer: module scripts defer by default. async changes scheduling, so leave it absent here. Our modules perform synchronous top-level initialization; this example does not establish completion rules for every graph containing top-level await.
This capture came from the exact example in Chrome 153: Tab focused the first button, then Space and Enter activated it. The view retained the same button element. Module scope kept count off window; looking for window.count would not inspect this store.
During comparison, a pending flag rejects duplicate activations while aria-busy reports the work. The focused button stays enabled, so temporary disabling does not throw away keyboard focus. Both successful and rejected imports clear the busy flag.
The initial disabled controls also provide an honest failure state. A broken entry leaves explanatory text and inactive buttons. The demonstration does not add a production error-reporting service or pretend the application mounted successfully.
Measure discovery separately from evaluation
I served fresh documents with artificial response delays of 180 milliseconds for the counter and 40 milliseconds for the view. The chart uses recorded browser request-start and loading-finished timestamps, rather than substituting those configured delays for measurements. All three requests returned JavaScript with status 200; the counter appeared once despite its two importers.
This is a local loading experiment, not a network benchmark. Parsing, scheduling and measurement overhead remain in the intervals. There is no claim about production latency, a mobile connection or bundler output. The useful observation is structural: the browser must obtain an importing module’s source to discover its static dependencies unless another mechanism has already supplied that information.
The console still reported counter, view, then main evaluation. A view response arriving earlier did not let the view read an uninitialized counter. Adding more imports therefore requires thinking about dependencies and initialization, not just arranging script tags in a visually pleasing order. Preloading and bundling are possible delivery decisions, but this experiment does not compare their performance.
Classify the failure before changing code
The following table summarizes isolated alterations to this graph. Each case used a fresh document, retained the initial disabled UI, and then attempted dynamic import to record the rejection category. Error wording is implementation-specific; these are observed Chrome categories, not universal strings to match in application logic.
For resolution, replace the counter specifier with an unmapped bare name such as counter-package. Browsers do not automatically search node_modules; use an import map or the project’s build-time resolver when that is the intended contract. For loading, inspect the requested URL, status, response body and MIME type. An HTTP 200 HTML fallback is still unsuitable JavaScript. Cross-origin modules additionally need the appropriate CORS response; the local second-port control succeeded when its response allowed the requesting origin.
For linking, import an absent named export from an otherwise valid counter. Downloading valid JavaScript does not guarantee compatible exports. For evaluation, throw inside the counter’s initializer. A graph can load and link yet fail while executing.
A cycle needs a more precise diagnosis than “cycles are forbidden.” Adding a side-effect import of view.mjs at the start of the counter makes this graph read count before its initialization, producing a ReferenceError. A separate control with the cyclic read deferred until after both modules initialized succeeded. Extract shared data or redesign initialization when possible; an arbitrary timer is not a dependency contract.
A different URL can mean different state
On a fresh page, activate the counter twice, then use “Compare module URLs.” The two identical imports return the same namespace object. The query-bearing URL returns a separate counter identity and changing that counter leaves the original count alone.
Repeat the comparison: the query copy advances from one to two. The code reuses the fixed ?copy=1 URL; it does not generate a new store on every click. A new document or frame has its own loading context, so the sharing claim is scoped to this document’s module graph. It is not a cross-tab database.
The same distinction can be inspected from the console. Reload before this diagnostic if you want the final commented value; the interface’s comparison also increments the query copy.
// Run in the browser console after opening the working example.
const shared = await import("/modules/counter.mjs");
const again = await import("/modules/counter.mjs");
const separate = await import("/modules/counter.mjs?copy=1");
console.log(shared === again); // true
console.log(shared.identity === separate.identity); // false
const before = shared.count;
separate.increment();
console.log(shared.count === before); // true
console.log(separate.count); // 1 on the first run in a fresh document
The dynamic import reference documents namespace reuse and query-based identities. Continually inventing fresh URLs is a poor substitute for explicit application state: it creates further module instances without an API to clear the namespace cache. If each widget needs an independent counter, export a factory that creates ordinary owned state instead.
Finally, dispose() removes both handlers and disables the controls. If a comparison import is pending, the active check prevents its later result from changing the copy or publishing output. It does not cancel fetching or unload an evaluated module. This separates the view’s lifetime from the module’s lifetime.
For an exercise, predict which values change when you activate the original button after three comparisons, then verify the prediction. Next, move only the HTML file and confirm the requested module URLs remain unchanged. These two small checks test state ownership and URL resolution independently, making a larger “module failed to load” report much easier to investigate.

