Dynamic Import in JavaScript
📦 What is Dynamic Import?
Dynamic import in JavaScript allows you to load modules *on-demand* using the import() function. Unlike static imports (which are loaded at the start), dynamic imports are fetched when needed — enabling code-splitting and lazy loading. 🚀
Note
🧠 It returns a promise that resolves to the module object.
🛠️ Syntax
Code Snippet
import('module-path').then((module) => {
// Use the module here
});✅ Example
Let's dynamically load a utility module only when it's needed:
Code Snippet
// File: utils.js
export function add(a, b) {
return a + b;
}Code Snippet
// File: main.js
button.addEventListener('click', async () => {
const utils = await import('./utils.js');
const result = utils.add(2, 3);
console.log('Sum:', result);
});Note
💡 This loads utils.js only when the button is clicked — saving initial load time.
🚀 Benefits
- Lazy Loading: Load code only when needed 💤
- Code Splitting: Reduce the size of initial bundles 📦
- Conditional Imports: Dynamically load modules based on conditions 🧠
🔀 Dynamic Path Example
You can also load modules conditionally:
Code Snippet
async function loadLib(libName) {
const module = await import(`./libs/${libName}.js`);
module.init();
}
loadLib("math"); // Dynamically loads './libs/math.js'Note
⚠️ The path passed to import() must be a full string (template strings allowed), not just a variable.
🧪 Using with `await`
Since import() returns a promise, you can use it with await inside async functions.
Code Snippet
const math = await import('./math.js');
console.log(math.sum(10, 20));📍 Real-World Use Cases
- 🧭 Load pages/components on user navigation
- 📊 Import heavy charting libraries only when needed
- 🔒 Conditionally import admin-only tools
🌐 Browser Support
Modern browsers support dynamic imports. For older browsers, use bundlers like Webpack or Rollup with polyfills.
🔗 Resources
>>“Load only what you need, when you need it.”