Lesson 75 - JavaScript Dynamic Imports
What You Will Learn
- What dynamic imports are
- How to use
import()
function in JavaScript - When and why to use dynamic imports
- Common use cases and benefits
What Are Dynamic Imports?
Normally, in JavaScript modules, you import dependencies at the top of the file using import
. These are static imports, and they must be resolved before the code runs.
Dynamic imports, on the other hand, allow you to load modules conditionally or at runtime using the import()
function.
Syntax of Dynamic Import
import('module-path')
.then(module => {
// Use the module
})
.catch(err => {
console.error("Failed to load module", err);
});
Or using async/await
:
async function loadModule() {
const module = await import('./mathUtils.js');
module.sayHello(); // assuming sayHello is exported
}
Why Use Dynamic Imports?
- Lazy loading: Load modules only when they’re needed
- Improve performance: Reduces initial page load time
- Conditional loading: Load a module based on user interaction or environment
- Better user experience: Faster time-to-interactive
Example: Conditional Module Loading
const themeButton = document.getElementById('theme-toggle');
themeButton.addEventListener('click', async () => {
const themeModule = await import('./darkTheme.js');
themeModule.enableDarkTheme(); // function from module
});
Try Your Hand
Create two files:
main.js
document.getElementById("load").addEventListener("click", async () => {
const math = await import('./math.js');
alert(`2 + 3 = ${math.add(2, 3)}`);
});
math.js
export function add(a, b) {
return a + b;
}
index.html
<button id="load">Load Math Module</button>
<script type="module" src="main.js"></script>
Click the button, and it dynamically loads the math module and shows the result.
Summary
Feature | Static Import | Dynamic Import |
---|---|---|
When loaded | At compile time | At runtime |
Syntax | import ... from |
import() |
Use case | Core dependencies | Lazy/conditional loading |
Supported in | All modern browsers | All modern browsers |