Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Awaiting on dynamic imports in JavaScript.
Dynamic imports in JavaScript allow you to load modules asynchronously at runtime using the import() function. This is particularly useful for code splitting and loading modules only when needed.
Syntax
const module = await import('./modulePath.js');
// or
import('./modulePath.js').then(module => {
// use module
});
How Dynamic Imports Work
The import() function returns a Promise that resolves to the module object. You can use await to handle it asynchronously:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Imports Example</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 20px;
}
.result {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
margin: 20px 0;
}
button {
padding: 10px 20px;
font-size: 16px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h1>Awaiting on Dynamic Imports</h1>
<div class="result"></div>
<button class="loadBtn">Load Module Dynamically</button>
<p>Click the button to dynamically import and execute module functions.</p>
<script>
document.querySelector(".loadBtn").addEventListener("click", loadModule);
let resultElement = document.querySelector(".result");
async function loadModule() {
try {
resultElement.innerHTML = "Loading module...<br>";
// Dynamic import with await
const module = await import('./sample.js');
// Use the imported functions
resultElement.innerHTML += module.testImport() + "<br>";
resultElement.innerHTML += "Current time: " + module.tellTime();
} catch (error) {
resultElement.innerHTML = "Error loading module: " + error.message;
}
}
</script>
</body>
</html>
Module File (sample.js)
function testImport() {
return "Module successfully imported and executed!";
}
function tellTime() {
return new Date().toLocaleString();
}
// Export the functions
export { testImport, tellTime };
Key Benefits
Dynamic imports offer several advantages:
- Code Splitting: Load modules only when needed, reducing initial bundle size
- Conditional Loading: Import modules based on runtime conditions
- Lazy Loading: Defer loading until user interaction or specific events
- Performance: Faster initial page load by splitting code into chunks
Example with Error Handling
<script>
async function loadModuleWithErrorHandling() {
try {
console.log("Starting dynamic import...");
const module = await import('./utilities.js');
// Access exported functions
if (module.formatDate) {
console.log("Formatted date:", module.formatDate(new Date()));
}
console.log("Module loaded successfully!");
} catch (error) {
console.error("Failed to load module:", error.message);
}
}
// Call the function
loadModuleWithErrorHandling();
</script>
Browser Compatibility
Dynamic imports are supported in modern browsers. For older browsers, you may need a polyfill or bundler support.
| Browser | Version | Support |
|---|---|---|
| Chrome | 63+ | Full |
| Firefox | 67+ | Full |
| Safari | 11.1+ | Full |
| Edge | 79+ | Full |
Conclusion
Dynamic imports with await provide a powerful way to load JavaScript modules asynchronously. They enable better performance through code splitting and allow for conditional module loading based on runtime requirements.
Advertisements
