Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Basic JavaScript

JS Tutorial JS Introduction JS Where To JS Output

JS Syntax

JS Syntax JS Statements JS Comments JS Variables JS Let JS Const JS Types

JS Operators

JS Operators JS Arithmetic JS Assignment JS Comparisons JS Conditional JS If JS If Else JS Ternary JS Switch JS Booleans JS Logical

JS Loops

JS Loops JS Loop for JS Loop while JS Break JS Continue JS Control Flow

JS Strings

JS Strings JS String Templates JS String Methods JS String Search JS String Reference

JS Numbers

JS Numbers JS Number Methods JS Number Properties JS Number Reference JS Bitwise JS BigInt

JS Functions

Function Path Function Intro Function Invocation Function Parameters Function Returns Function Arguments Function Expressions Function Arrow Function Quiz

JS Objects

Object Path Object Intro Object Properties Object Methods Object this Object Display Object Constructors

JS Scope

JS Scope JS Code Blocks JS Hoisting JS Strict Mode

JS Dates

JS Dates JS Date Formats JS Date Get JS Date Set JS Date Methods

JS Arrays

JS Arrays JS Array Methods JS Array Search JS Array Sort JS Array Iterations JS Array Reference JS Array Const

JS Sets

JS Sets JS Set Methods JS Set Logic JS Set WeakSet JS Set Reference

JS Maps

JS Maps JS Map Methods JS Map WeakMap JS Map Reference

JS Iterations

JS Loops JS Iterables JS Iterators JS Generators

JS Math

JS Math JS Math Reference JS Math Random

JS RexExp

JS RegExp JS RegExp Flags JS RegExp Classes JS RegExp Metachars JS RegExp Assertions JS RegExp Quantifiers JS RegExp Patterns JS RegExp Objects JS RegExp Methods

JS Data Types

JS Destructuring JS Data Types JS Primitive Data JS Object Types JS typeof JS toString JS Type Conversion

JS Errors

JS Errors Intro JS Errors Silent JS Error Statements JS Error Object

JS Debugging

Debugging Intro Debugging Console Debugging Breakpoints Debugging Errors Debugging Async Debugging Reference

JS Conventions

JS Style Guide JS Best Practices JS Mistakes JS Performance

JS References

JS Statements JS Reserved Keywords JS Operators JS Precedence

JS Versions

JS 2026 JS 2025 JS 2024 JS 2023 JS 2022 JS 2021 JS 2020 JS 2019 JS 2018 JS 2017 JS 2016 JS Versions JS 2015 (ES6) JS 2009 (ES5) JS 1999 (ES3) JS IE / Edge JS History

JS HTML

JS HTML DOM JS Events JS Projects New

JS Advanced

JS Temporal  New JS Functions JS Objects JS Classes JS Asynchronous JS Modules JS Meta & Proxy JS Typed Arrays JS DOM Navigation JS Windows JS Web APIs JS AJAX JS JSON JS jQuery JS Graphics JS Examples JS Reference


JavaScript Dynamic Modules

JavaScript Dynamic Import

Dynamic Import uses the syntax:

import(module);

Dynamic Import was introduced in ECMAScript 2020

Dynamic Import is a way to load JavaScript modules at runtime, rather than at the start of your program.

Modern Software

Modern software splits imports into separate chunks.

Modules are downloaded only when requested - this method has many names:.

  • Dynamic Import
  • Code Splitting
  • Lazy Loading
  • Conditional Loading

Dynamic import is one of the most powerful features for modular and efficient code.

Unlike Static Import (which must appear at the top of a file), Dynamic Import can be used anywhere - inside functions, conditionals, event handlers, etc.

Syntax

import("./module.js")
  • The argument must be a string or expression that resolves to a path
  • You must run the import inside a module script (<script type="module">)
TypeExampleWhen Loaded
Staticimport { add } from './math.js'; At load time
Dynamicconst math = await import('./math.js'); When needed

Improved Performance

Modules can improve performance by allowing tools to implement "code splitting". This means that a user's browser only needs to load the JavaScript modules required for the specific features they are using at a given moment, rather than the entire application's code at once.

While modules themselves are a language feature, when combined with bundlers like Webpack or Rollup, they can lead to performance improvements through optimizations like tree-shaking (eliminating unused code), code splitting, and minification.


How Dynamic Import Works

Dynamic Modules use modern async/await:

Example

async function run() {
  const module = await import("./math.js");
  let result = module.add(2, 3);
}
run();

Try it Yourself »

math.js

// Export an "add" function
export function add(a, b) {
  return a + b;
}

Example Explained

  • The script starts running
  • It defines and calls run()
  • Inside run(), it dynamically loads math.js
  • Once loaded, it gets access to the exported function add()
  • It calls add(2, 3) and gets 5
  • It displays the result
StepCodeExplained
1async function run()Define a function that can use await
2await import("./math.js")Load the module file only when needed
3module.add(2, 3)Use the exported function from the module
4run()Start the process

Step 1. Define a function that can use await:

async function run() {
  • This line defines an asynchronous function called run()
  • The async keyword means the function can use await inside it
  • The await keyword pauses the function until a Promise is resolved
  • In this case, the Promise is the import of the module

Step 2. Load the module file only when needed:

const module = await import("./math.js");
  • import("./math.js") defines a dynamic import
  • The module math.js is loaded on demand
  • math.js returns a Promise that resolves to its exported content
  • The await keyword waits until the module is fully loaded
  • Once loaded, the variable module contains the data exported from math.js

Step 3. Use the exported function from the module:

let result = module.add(2, 3);
  • Calls the exported function add() from the imported module
  • Passes in 2 and 3 as arguments
  • The function adds them and returns 5
  • The result is stored in result

Step 4. Start the process - Call the Function:

run();

When it runs:

  1. It loads the module math.js dynamically
  2. It waits for the module to finish loading
  3. It calls the add() function of the module
  4. It displays the result


Another Example

Example

async function run(x) {
  const module = await import("./temperatures.js");
  let celsius = module.toCelsius(x);
  document.getElementById("demo").textContent = celsius + " Celcius";
}
run(50);

Try it Yourself »

temperatures.js

// Convert Fahrenheit to Celsius
export function toCelsius(farenheit) {
  return (farenheit - 32) * 5 / 9;
}

// Convert Celsius to Fahrenheit
export function toFahrenheit(celsius) {
  return (celsius * 9 / 5) + 32;
}

Dynamic Import Key Features

  • Lazy Loading - Load code only when it is needed
  • Performance Optimization - Reduce initial load size for faster page load
  • Conditional Imports - Import different modules based on conditions.

Conditional Loading

if (user.isAdmin) {
  const adminTools = await import("./admin-tools.js");
  adminTools.init();
}

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

-->