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
Loading JavaScript modules dynamically
Dynamic module loading allows you to import JavaScript modules at runtime rather than at compile time. This enables lazy loading, conditional imports, and better performance optimization.
Static vs Dynamic Import
Static imports happen at the top of files and load immediately. Dynamic imports use the import() function to load modules on demand.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Module Loading</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
margin: 20px;
}
.result {
font-size: 18px;
font-weight: 500;
margin: 20px 0;
padding: 10px;
background: #f0f0f0;
border-radius: 5px;
}
button {
padding: 10px 20px;
font-size: 16px;
background: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Dynamic Module Loading Example</h1>
<button onclick="loadModule()">Load Math Module</button>
<div class="result" id="result">Click button to dynamically load module</div>
<script>
async function loadModule() {
try {
// Dynamic import using import() function
const mathModule = await import('./math.js');
// Use the imported functions
const sum = mathModule.add(5, 3);
const product = mathModule.multiply(4, 7);
document.getElementById('result').innerHTML =
`Module loaded! Sum: ${sum}, Product: ${product}`;
console.log('Math module loaded successfully');
} catch (error) {
console.error('Failed to load module:', error);
document.getElementById('result').innerHTML =
'Failed to load module';
}
}
</script>
</body>
</html>
Math Module (math.js)
// math.js - Module to be loaded dynamically
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
export function subtract(a, b) {
return a - b;
}
console.log('Math module has been loaded');
Conditional Module Loading
Dynamic imports are useful for loading modules based on conditions:
<!DOCTYPE html>
<html>
<head>
<title>Conditional Loading</title>
</head>
<body>
<button onclick="loadBasedOnCondition()">Smart Load</button>
<div id="output"></div>
<script>
async function loadBasedOnCondition() {
const userAgent = navigator.userAgent;
let module;
if (userAgent.includes('Mobile')) {
// Load mobile-specific module
module = await import('./mobile-utils.js');
document.getElementById('output').innerHTML =
'Mobile module loaded';
} else {
// Load desktop module
module = await import('./desktop-utils.js');
document.getElementById('output').innerHTML =
'Desktop module loaded';
}
// Use the loaded module
module.initialize();
}
</script>
</body>
</html>
Benefits of Dynamic Loading
| Feature | Static Import | Dynamic Import |
|---|---|---|
| Load Time | At parse time | At runtime |
| Conditional Loading | No | Yes |
| Code Splitting | Limited | Excellent |
| Performance | Immediate | Lazy loading |
Error Handling
Always wrap dynamic imports in try-catch blocks to handle loading failures:
async function safeModuleLoad() {
try {
const module = await import('./optional-feature.js');
module.initializeFeature();
} catch (error) {
console.warn('Optional feature not available:', error.message);
// Fallback behavior
initializeFallback();
}
}
Conclusion
Dynamic module loading with import() enables lazy loading, conditional imports, and better performance. Use it for optional features, code splitting, and progressive enhancement of your applications.
Advertisements
