0
0
JavascriptConceptBeginner · 3 min read

Dynamic Import in JavaScript: What It Is and How It Works

In JavaScript, dynamic import allows you to load modules asynchronously at runtime instead of loading them all upfront. It uses the syntax import() which returns a promise that resolves to the module, enabling code to be loaded only when needed.
⚙️

How It Works

Dynamic import in JavaScript works like ordering food at a restaurant only when you want to eat, instead of ordering everything at once. Normally, JavaScript imports all modules before running the code, which can slow down the start time. With dynamic import, the program waits until it actually needs a module, then fetches it.

This is done using the import() function, which returns a promise. When the promise resolves, you get access to the module's exports. This means your app can load faster and use less memory initially, improving performance especially for big apps.

💻

Example

This example shows how to dynamically import a module named mathUtils.js only when a function is called.

javascript
async function calculate() {
  const mathUtils = await import('./mathUtils.js');
  console.log('Sum:', mathUtils.add(5, 3));
}

calculate();
Output
Sum: 8
🎯

When to Use

Use dynamic import when you want to improve your app's loading speed by loading code only when needed. For example, load a heavy charting library only when the user opens the chart page, or load admin tools only for users with special access.

This helps reduce the initial download size and speeds up the app start, making the user experience smoother.

Key Points

  • Dynamic import uses import() and returns a promise.
  • It allows loading modules on demand, not upfront.
  • Improves app performance by reducing initial load time.
  • Useful for large apps or rarely used features.

Key Takeaways

Dynamic import loads JavaScript modules asynchronously at runtime using import().
It returns a promise that resolves to the module, enabling on-demand loading.
Use it to improve app speed by loading code only when needed.
Ideal for large apps or features used infrequently.
Helps reduce initial download size and memory usage.