🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript Dynamic import

A dynamic import is an import call that runs while the program runs. It loads a module only when the code reaches it.

Import only when needed

The import sits inside a small function. The first line prints before the import, and the module message prints after it.

(async () => {
  const load = async () => {
    const url = URL.createObjectURL(new Blob(["export const message = 'Loaded when needed';"], { type: "text/javascript" }));
    const module = await import(url);
    return module.message;
  };
  console.log("Before import");
  console.log(await load());
})();

A failed import is caught

The Blob holds broken module code, so the import throws a SyntaxError. The error is caught, and the program keeps running.

(async () => {
  try {
    const url = URL.createObjectURL(new Blob(["export const = ;"], { type: "text/javascript" }));
    await import(url);
  } catch (err) {
    console.log(err.name);
  }
  console.log("Still running");
})();

Choose a module from a value

The choice value picks which module text to load. The loaded module doubles 21, which gives 42.

(async () => {
  const choice = "double";
  let code = "export const run = (n) => n * 3;";
  if (choice === "double") {
    code = "export const run = (n) => n * 2;";
  }
  const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
  const module = await import(url);
  console.log(module.run(21));
})();

Example

(async () => {
  const needHelp = true;
  if (needHelp) {
    const url = URL.createObjectURL(new Blob(["export const tip = 'Split the work into small steps.';"], { type: "text/javascript" }));
    const help = await import(url);
    console.log(help.tip);
  }
  console.log("Done");
})();

Key points

  • Dynamic import: an import call that runs while the program runs
  • The code waits for a dynamic import, then reads the loaded module.
  • A dynamic import loads a module only when it is needed, not at the start.
  • When a module fails to load, the import throws an error, so try and catch can handle it.
  • A dynamic import can choose which module to load from a value in the program.
  • A dynamic import is written as import with round brackets around the address.

In this example, the program imports a help module only when help is needed. The flag decides whether the import runs at all. The last line prints after the import, which shows the main program kept going.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

When does a dynamic import load its module?