bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

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

Example

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

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

  • It loads the module math.js dynamically
  • It waits for the module to finish loading
  • It calls the add() function of the module
  • 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);

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();
}

Previous

JS Module Namespace

Next

JavaScript Meta Programming

This chapter

Overview
123

Lessons

539m

Read time

1. JavaScript Objects2. JavaScript Temporal Tutorial3. JavaScript Loops4. JavaScript Advanced Functions5. JavaScript Objects6. JavaScript Temporal Intro7. JavaScript Iterables8. JavaScript Function Definitions9. JavaScript Object Properties10. JavaScript Temporal vs Date11. JavaScript Iterators12. JavaScript Callbacks13. JavaScript Object Methods14. JavaScript Temporal Duration15. JavaScript Generators16. The JavaScript this Keyword17. JavaScript this Keyword18. JavaScript Temporal Instant19. JavaScript Function call()20. JavaScript Display Objects21. JavaScript PlainDateTime22. JavaScript Function apply()23. JavaScript Object Constructors24. JavaScript Temporal PlainDate25. JavaScript Function bind()26. JavaScript PlainYearMonth27. Self-Invoking Functions28. JavaScript PlainMonthDay29. JavaScript Closures30. JavaScript Temporal PlainTime31. JavaScript Objects - Advanced32. JavaScript ZonedDateTime33. JavaScript Object Definitions34. JavaScript Temporal Now35. this in JavaScript Objects36. JS Temporal Arithmetic37. JavaScript Object Iterations38. JS Temporal Differences39. JavaScript Object Accessors40. JS Temporal Compare41. JavaScript Object Management42. JavaScript Temporal Conversion43. JavaScript Object Protection44. Temporal Display Formats45. JavaScript Object Prototypes46. JavaScript Temporal Mistakes47. JavaScript Classes48. Migrate from Date to Temporal49. JavaScript Class Inheritance50. Temporal Standards51. JavaScript Static Methods52. Asynchronous JavaScript53. Asynchronous Programming54. JavaScript Timeouts55. JavaScript Callbacks56. JavaScript Promises57. JavaScript async and await58. JavaScript fetch API59. Debugging Async JavaScript60. JavaScript Modules61. JavaScript Modules Export62. JavaScript Modules Import63. JS Module Namespace64. JavaScript Dynamic Modules65. JavaScript Meta Programming66. JavaScript Reflect67. JavaScript Proxy68. JavaScript Typed Arrays69. Typed Array Methods70. JavaScript ArrayBuffer71. JavaScript DataView72. JavaScript Atomics73. JavaScript HTML DOM Navigation74. JavaScript HTML DOM Elements (Nodes)75. JavaScript HTML DOM Collections76. JavaScript HTML DOM Node Lists77. JavaScript Window - The Browser Object Model78. JavaScript Window Screen79. JavaScript Window Location80. JavaScript Window History81. JavaScript Window Navigator82. JavaScript Popup Boxes83. JavaScript Timing Events84. JavaScript Cookies85. Web APIs - Introduction86. JavaScript Fetch API87. Web Geolocation API88. Web History API89. Pointer Events API90. Web Storage API91. JavaScript Validation API92. Web Workers API93. AJAX Introduction94. AJAX - The XMLHttpRequest Object95. AJAX - XMLHttpRequest96. AJAX - Server Response97. AJAX XML Example98. AJAX PHP Example99. AJAX ASP Example100. AJAX Database Example101. XML Applications102. JavaScript JSON103. JSON Syntax104. JSON vs XML105. JSON Data Types106. JSON.parse()107. JSON.stringify()108. JSON Object Literals109. JSON Array Literals110. JSON PHP111. JSON HTML112. JSONP113. JavaScript / jQuery DOM Selectors114. JavaScript / jQuery HTML Elements115. JavaScript / jQuery CSS Styles116. JavaScript / jQuery HTML DOM117. JavaScript Graphics118. HTML Canvas119. Plotly.js120. Chart.js121. Google Chart122. D3.js123. JavaScript Interview Preparation

On this page

JavaScript Dynamic ImportModern SoftwareImproved PerformanceHow Dynamic Import WorksExample ExplainedAnother ExampleDynamic Import Key FeaturesConditional Loading