Loading Code On Demand
Regular import statements are static — they must be at the top of the file and all modules are loaded upfront. This can slow down initial page load.
The Dynamic import() Function
Loads a module lazily, at any point during code execution — like clicking a button or navigating to a page.
// Load the chart library only when the user opens the reports section
async function openReports() {
const { renderChart } = await import('./chart-library.js');
renderChart(document.querySelector('#chart'), data);
}
// Load based on user language preference
async function loadTranslations(lang) {
const translations = await import(`./locales/${lang}.js`);
applyTranslations(translations.default);
}
Benefits
- Save bandwidth: Load heavy code only when actually needed.
- Faster initial load: Smaller main bundle = faster first page render.
- Route-based splitting: In React/Vue apps, each page can load its own code independently.
Note
import() returns a Promise that resolves to the module object. Use it with async/await or .then().
Tip
This pattern is called lazy loading or code splitting and is a key optimization technique in modern web apps. Frameworks like Next.js and Nuxt use it automatically.