0Pricing
HTML Academy · Lesson

Dynamic Import() in Modules

Load modules on demand with dynamic import().

The import() Expression

Unlike the static import declaration, import("./module.js") is an expression that returns a Promise resolving to the module's namespace. It works anywhere — inside functions, conditions, even inside non-module scripts.

Code Splitting

Dynamic import is the primary code-splitting mechanism. A route handler can defer loading the route's code until the user navigates: const mod = await import("./routes/admin.js"). The route's bytes never download until they are needed.

document.getElementById("settings-btn").addEventListener("click", async () => {
  const { renderSettings } = await import("./settings.js");
  renderSettings();
});

All lessons in this course

  1. ES Module Scripts type=module
  2. Import Maps importmap
  3. Dynamic Import() in Modules
  4. Module Federation Basics
← Back to HTML Academy