JavaScript Modules
JavaScript Dynamic Import
Dynamic Import was introduced in ECMAScript 2020
Dynamic import is one of the most powerful features for modular and efficient code.
Dynamic Import is a way to load JavaScript modules at runtime, rather than at the start of your program.
Unlike Static Import (which must appear at the top of a file), Dynamic Import can be used anywhere - inside functions, conditionals, event handlers, etc.
Syntax
import("./module.js")
- The argument must be a string or expression that resolves to a path
- You must run the import inside a module script (<script type="module">)
| Type | Example | When Loaded |
|---|---|---|
| Static | import { add } from './math.js'; |
At load time |
| Dynamic | const math = await import('./math.js'); |
When needed |
Modern Software
Modern software splits dynamic imports into separate chunks.
Modules are downloaded only when requested - this method has many names:.
- Dynamic Import
- Code Splitting
- Lazy Loading
- Conditional Loading
Note
Modules operate in strict mode by default.
How Dynamic Import Works
The import() function returns a Promise that resolves to the module's exports:
import("./math.js")
.then((module) => {
// Access exported function
result = module.add(2, 3);
})
.catch((err) => {
console.error("Failed to load module:", err);
});
Or using async/await:
async function run() {
const module = await import("./math.js");
result = module.add(2, 3);
}
run();
Conditional Loading
if (user.isAdmin) {
const adminTools = await import("./admin-tools.js");
adminTools.init();
}
Dynamic Import Key Features
- Lazy Loading - Load code only when it is needed
- Performance Optimization - Reduce initial load size for faster page load
- Conditional Imports - Import different modules based on conditions.