Dynamic Imports
import() is a function that loads a module at runtime. It returns a Promise, enabling lazy loading and code splitting.
import() is a function that loads a module at runtime. It returns a Promise, enabling lazy loading and code splitting.
// 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);
}
Dynamic imports are the foundation of code splitting — bundle only what each page needs on the client.
More in JavaScript