Dynamic Import Syntax and Promises
You'll learn how the import() function returns a promise that resolves to a module once it's loaded, enabling truly dynamic code loading.
The Core Idea
Unlike static imports that load at the top of your file, the import() function is dynamic—it's called like a regular function at runtime and returns a promise. This promise resolves to the module object once the browser has fetched and parsed the code.
Think of it like ordering food for delivery: you place the order (import()), get a promise that food will arrive, then when it shows up (promise resolves), you can use it.
How It Works
// Static import - happens immediately
// import { heavyFunction } from './heavy-module.js';
// Dynamic import - happens when called
import('./heavy-module.js')
.then(module => {
// Promise resolved! Module is ready
module.heavyFunction();
})
.catch(error => {
console.error('Failed to load module:', error);
});
Since import() returns a promise, you can also use async/await syntax:
async function loadAndRun() {
try {
const module = await import('./heavy-module.js');
module.heavyFunction();
} catch (error) {
console.error('Failed to load module:', error);
}
}
Why This Matters
The promise-based nature means you can:
- Load modules conditionally based on user actions
- Handle loading failures gracefully
- Show loading indicators while modules fetch
- Chain multiple dynamic imports
- Load modules only when network conditions are favorable
Key Takeaway: The import() function returns a promise that resolves to your module, giving you full control over when and how code loads—essential for performance optimization in modern web applications.