Blog>
Snippets

Dynamic imports for lazy loading

Illustrate the use of dynamic imports to lazily load a module only when it's required for the execution.
// Assume we have a module named 'mathModule.js' which exports a function 'add'

// Function to load the module dynamically
async function loadMathModule() {
  // Using dynamic import syntax to import 'mathModule.js' when needed
  const math = await import('./mathModule.js');
  return math;
}

// Event handler or any other scenario where we need the 'add' function
async function handleCalculation() {
  // Importing only when the function is needed, thus lazily loading it
  const math = await loadMathModule();
  console.log('3 + 4 =', math.add(3, 4));
}

// Call the function that requires the dynamically imported module
handleCalculation();
This piece of JavaScript code defines an asynchronous function, loadMathModule(), that uses the dynamic import() function to load a module named 'mathModule.js' when it's required. The handleCalculation() function demonstrates how the module can be loaded lazily, and only when the calculation is needed. It loads the module, uses the exported 'add' function, and logs the result. The handleCalculation() function is then called at the end.