Skip to main content
Dynamic import is a function-like expression in JavaScript that asynchronously loads an ECMAScript module at runtime. Unlike static import declarations—which are statically analyzed, resolved, and linked into a dependency graph prior to execution—dynamic imports return a Promise and can be executed conditionally or on-demand within any lexical scope. While the actual evaluation of the module code happens at runtime for both, static imports are evaluated strictly before the importing module executes, whereas dynamic imports are evaluated exactly when the import() expression is invoked.

Syntax

  • moduleSpecifier: A string, or an expression that evaluates to a string, representing the path to the module.
  • options (Optional): An object containing import options. This is standardly used for Import Attributes to specify the module format or type.

Technical Mechanics

When the JavaScript engine encounters an import() expression, it initiates the fetch, instantiation, and evaluation of the target module asynchronously. 1. The Module Namespace Object and Live Bindings The Promise returned by import() resolves to a module namespace object. Crucially, this object does not act as a static snapshot; it provides live bindings to the exports of the requested module. If an exported variable is updated from within the loaded module, the new value is immediately reflected on the module namespace object returned by the dynamic import.
Because default is a reserved keyword in JavaScript, you must alias it when destructuring the module namespace object:
2. Import Attributes The optional second argument allows the passing of attributes to the module loader, dictating how the module should be parsed and instantiated.
3. Runtime Specifier Evaluation Because dynamic imports are resolved at runtime, the moduleSpecifier does not need to be a static string literal. It can be a dynamically computed value, such as a variable or a template literal.
4. Lexical Placement Static import statements are strictly constrained to the top level of a module to allow the JavaScript engine to statically analyze the dependency graph and create Module Records before execution. Dynamic import() bypasses this constraint and can be placed inside functions, if statements, try/catch blocks, or loops.

Static vs. Dynamic Import Comparison

Caching Behavior

The JavaScript engine maintains a module map. If import() is called multiple times with the same resolved moduleSpecifier, the engine fetches, instantiates, and evaluates the module only once. Subsequent calls return a Promise that resolves immediately with the already-cached module namespace object.
Tired of Poor JavaScript Skills? Fix That With Deep Grasping!Learn More