SyntaxStudy
Sign Up
JavaScript Intermediate 5 min read

Dynamic import()

Dynamic Imports

import() is a function that loads a module at runtime. It returns a Promise, enabling lazy loading and code splitting.

Example
// Load only when needed
button.addEventListener("click", async () => {
  const { Chart } = await import("./chart.js");
  new Chart(canvas, config);
});

// Conditional loading
if (userPreferences.showMap) {
  const { initMap } = await import("./map.js");
  initMap();
}

// With error handling
try {
  const module = await import("./plugin.js");
  module.init();
} catch (e) {
  console.error("Plugin load failed:", e);
}
Pro Tip

Dynamic imports are the foundation of code splitting — bundle only what each page needs on the client.