Module Loading and Execution Order
You'll learn how top-level await changes the way ES modules load and execute, affecting the timing of your entire dependency graph.
How Modules Load Normally
Before top-level await, ES modules loaded in a predictable, synchronous manner. When you import modules, JavaScript builds a dependency graph and executes them in dependency order: deepest dependencies first, then their parents, moving upward. Every module runs to completion immediately, and the execution is synchronous.
The Top-Level Await Impact
When a module uses top-level await, it becomes asynchronous. The module pauses at the await point, allowing its Promise to settle before continuing. This has a cascading effect:
Any module that imports an async module must wait for it to finish before that importing module can complete its own execution. The entire loading chain pauses.
The Ripple Effect
Think of module loading like a relay race. Normally, each runner (module) immediately hands off the baton (execution) to the next. But with top-level await, one runner stops to tie their shoe (await a Promise), and everyone behind them must wait, even if they don't have async code themselves.
If moduleA imports moduleB, and moduleB has a top-level await, then moduleA won't finish loading until moduleB's await completes. This happens automatically—moduleA doesn't need to use await itself.
Execution Order Example
- Module C has no dependencies → executes first
- Module B imports C → executes after C
- Module A imports B (which has top-level await) → A waits for B's async operation
- Main module imports A → it too must wait for the entire chain
Key Takeaway: Top-level await blocks the execution of all importing modules, turning your entire dependency subtree asynchronous and potentially delaying application startup.