CodeBlanks Logo Icon CodeBlanks

Dynamic import

JavaScript course · Advanced · Lesson 1/100

Learn to load a module at runtime with the import() expression.

What is dynamic import?

Dynamic import loads a module at runtime with the import() expression. A static import loads up front; import() loads only when you call it.

import() returns a promise, so it is used with await. When the module is ready, the promise resolves and you get its exported values.

This is used for lazy loading code on demand and for splitting large bundles into smaller pieces.

Using it with await

To load a module at runtime, you call import() with await. The result is an object holding the module's exported values.

const mod = await import('./heavy.js');
console.log(mod.draw());

Here heavy.js loads only when this line runs, not when the page opens. This keeps the first load fast.

Exercise Load a module at runtime

Load the ./chart.js module at runtime with await import() and assign it to a variable named chart. Then log the result of chart.draw() with console.log.

Show example solution
Load with await import, assign to chart, then call draw.
Example solution:
const chart = await import('./chart.js');
console.log(chart.draw());

Test yourself

  1. What does the import() expression return?

    • an array
    • a promise
    • a number
    • a boolean
    Show answer

    a promise — Correct! import() returns a promise; you await it.

  2. Complete the dynamic import

    const mod = ____('./heavy.js');
    Show answer
    const mod = await import('./heavy.js');
  3. Match the concepts

    import()
    loads at runtime
    await
    waits for a promise
    static import
    loads up front
    promise
    returned by import()

All lessons in Advanced