freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #54 of 61

dynamic import · code splitting

LambdaVSThe Mutator
Lambda saysDynamic import() loads a module on demand and returns a promise — enabling code splitting.

Static import is hoisted and always loads. import('./heavy.js') is a function that returns a promise, so you can load code only when needed (a route, a click), shrinking the initial bundle. Pair with await. This is the foundation of lazy loading and route-based code splitting.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleSketch loading a module on a button click with await import().

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre>btn.onclick = async () => {
  const { chart } = await import('./chart.js'); // loaded only on click
  chart();
};</pre></body></html>
▶ Open the interactive comic issue
‹ Modules · Default Vs NamedModules · Re-Exports · Barrel Files ›