It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

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