JavaScript - Dynamic Imports
Overview
Estimated time: 15–20 minutes
Dynamic import()
lets you load modules on demand, enabling code splitting and lazy loading for better performance.
Learning Objectives
- Use
import()
to load modules dynamically. - Understand use cases for dynamic imports.
Prerequisites
Syntax
import('./math.js').then(module => {
console.log(module.add(2, 3));
});
Use Cases
- Lazy loading code only when needed (e.g., on user action).
- Loading large libraries on demand.
- Reducing initial page load time.
Example
// Only load math.js when button is clicked
button.addEventListener('click', async () => {
const math = await import('./math.js');
alert(math.add(1, 2));
});
Common Pitfalls
- Dynamic import returns a promise; use
await
orthen
. - File paths must be correct and served over HTTP(s).
Summary
Dynamic imports enable advanced loading strategies and are essential for modern web apps.