Dynamic Import, Top-Level Await, and `import.meta`
Loading a module on demand with `import()`, using `await` at a module's top level instead of only inside `async` functions, and what `import.meta` tells you.
Dynamic Import, Top-Level Await, and `import.meta`
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `import()` is a function, not a statement — it takes a module specifier and returns a promise that resolves to that module's exports, which means you can call it conditionally, in a loop, or in response to an event, none of which a static `import` statement allows.
- The main reason to reach for `import()` is to defer the cost of a module you might not need yet — a chart library only required if the user opens a dashboard tab, a heavy parser only needed for one rare code path — so the initial load doesn't pay for code nobody's using.
- Top-level `await` lets a module pause its own evaluation on a promise, at the top level, without wrapping that line in an `async` function — the module simply isn't considered "ready" until the awaited promise settles, and anything importing it waits too.
- `import.meta` is an object every module gets for free, holding metadata about itself — `import.meta.url` is the big one, giving a module its own absolute location so it can resolve a path (a data file, an image) relative to where it lives instead of relative to whatever file happens to be running it.
- Both features only exist inside real ES modules — top-level `await` in a classic script is a syntax error, and `import.meta` outside a module context doesn't exist at all.
A static import can’t say “maybe”
Every import statement you’ve written so far sits at the top of a file,
unconditional, resolved before your code even starts running. That’s a
deliberate restriction — it’s what lets a bundler read a module’s entire
dependency graph without executing anything — but it also means a static
import can’t express “load this only if the user clicks the button” or
“load whichever of these three modules matches a runtime condition.” The
syntax has no way to make importing conditional, because conditional logic
doesn’t exist yet when imports get resolved.
import() fixes that by being a completely different kind of thing: not a
statement, a function call. import("./chart.js") can appear inside an
if, inside a loop, inside a click handler — anywhere an ordinary function
call is legal — and it returns a promise that resolves to the module’s
exports once the module has been fetched and run.
button.addEventListener("click", async () => {
const { renderChart } = await import("./chart.js");
renderChart(data);
});
Nobody downloads or parses chart.js until someone actually clicks the
button. That’s the whole value proposition: code-splitting and lazy
loading aren’t bundler magic layered on top of JavaScript — import() is
the language-level feature that makes them possible at all. A bundler
still decides how to physically chunk your files, and that mechanical side
belongs to tooling, not this lesson, but the hook it’s hanging off is this
one function.
The video is a tight walkthrough of exactly this: what dynamic imports are, and three concrete reasons to reach for one — code splitting, cutting memory usage, and keeping the rest of your code fast by not making it wait on something it doesn’t need yet. Watching those examples land is more convincing than any abstract argument for “lazy loading is good.”
Top-level await: a module that isn’t ready until it’s ready
await has always been restricted to async functions — you couldn’t
write it at a file’s top level, outside any function, because there was
nowhere for the pause to go. Top-level await removes that restriction,
but only inside a real ES module:
// config.js
const response = await fetch("/api/config");
export const config = await response.json();
Here’s the part that makes this more than syntactic convenience: a module
using top-level await isn’t considered finished evaluating until that
await resolves. Anything that imports config.js automatically waits for
it, the same way it would wait for any other synchronous module to finish
running. You get the ergonomics of async/await applied to module
initialization itself, without wrapping the whole file in an IIFE and
exporting a promise that every importer then has to remember to await
separately — which is the workaround this feature replaced.
The restriction to real modules isn’t an arbitrary rule. A classic
<script> tag has no concept of “pausing evaluation” for anything outside
a function — the whole page’s script execution model assumes synchronous,
top-to-bottom completion. Modules already have their own evaluation phase
with dependency ordering built in, so there was somewhere sensible to hang
an await onto. Try it in a non-module script and you get a syntax error,
not a runtime surprise.
import.meta: a module’s ID card
Every module gets one more thing for free: import.meta, an object
holding metadata about that specific module — not about whoever happens
to be importing it. The property you’ll actually use is import.meta.url,
which holds the module’s own absolute URL (or file path, in Node).
Why does that matter? A relative path like ./data.json only means
something relative to whichever file is currently resolving it — and once
your module gets imported by something three layers deep in someone else’s
dependency tree, “relative to the file running right now” stops being a
reliable way to find a file that lives next to your module. import.meta.url
sidesteps that entirely: it’s always the real location of the file it’s
read in, so you can build a path from it that’s correct regardless of who
imported you or from where.
// inside widgets/logo.js
const logoPath = new URL("./logo.svg", import.meta.url);
That gives you a correct, absolute path to logo.svg sitting next to
logo.js, no matter which other file eventually imports logo.js or how
deeply nested that import is.
Where this fits
All three of these — import(), top-level await, and import.meta —
are only meaningful once you already have ES modules
and async/await in hand; they’re
refinements on top of those two foundations, not separate ideas. This
lesson stays at what the language itself guarantees — the promise
import() returns, the evaluation-order contract top-level await gives
you, the metadata object every module carries. How a bundler physically
splits files into chunks, and how Node specifically resolves module URLs
on disk, are mechanics that belong to tooling and to nodejs, not here.
Check yourself
What does `import("./chart.js")` actually return, and how is that different from a regular `import` statement at the top of a file?
It returns a promise that resolves to the module's exports object once `chart.js` has been fetched and evaluated. A static `import` statement isn't an expression at all — it's resolved before any code runs, at the top level only, and can't be placed inside an `if` or a function. `import()` is an ordinary function call, so it can go anywhere a function call can, including conditionally.
Why would a web app use `import()` for a feature like a PDF export button instead of importing the PDF library normally at the top of the file?
Importing it statically means every visitor downloads and parses that library on page load, whether or not they ever click the button. `import("./pdf-export.js")` inside the button's click handler means the cost — the network request, the parse time — is only paid by someone who actually uses the feature, which keeps the initial page load lighter for everyone else.
A module does `const config = await fetch("/config.json").then(r => r.json());` at its top level, outside any function. Why does this work in a module but not in a plain `<script>` tag?
Top-level `await` is only legal inside an ES module (a file loaded with `type="module"`, or a `.mjs` file in Node). A module is allowed to pause its own evaluation on a pending promise, and anything importing that module automatically waits for it to finish before proceeding. A classic script has no such evaluation-pausing mechanism, so `await` outside an `async` function there is just a syntax error.
What problem does `import.meta.url` solve that you couldn't solve with a hardcoded relative path?
A relative path like `./data.json` is resolved relative to whatever file is currently running the code that uses it — which, in a bundled or re-exported module, might not be the file you wrote it in. `import.meta.url` gives a module its own real, absolute location, so you can build a path relative to *that specific file* regardless of who imported it or how deeply it's nested in a dependency tree.
If `import('./math.js')` is called twice from two different files, does `math.js` run its top-level code twice?
No. Like static imports, dynamic imports share the same module cache — the specifier is resolved to one canonical module record, so the module's body executes once, and every subsequent `import()` or `import` of it (dynamic or static) resolves to the same already-evaluated module and its same exported bindings.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.