> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript Dynamic Import

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

```javascript theme={"dark"}
import(moduleSpecifier)
import(moduleSpecifier, options)
```

* **`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.

```javascript theme={"dark"}
// Using async/await
async function loadMath() {
  try {
    const mathModule = await import('./math.js');
    
    // Accessing a named export
    const sum = mathModule.add(5, 10);
    
    // Accessing the default export
    const defaultVal = mathModule.default();
  } catch (error) {
    console.error("Failed to load module:", error);
  }
}
```

Because `default` is a reserved keyword in JavaScript, you must alias it when destructuring the module namespace object:

```javascript theme={"dark"}
const { default: DefaultClass, namedFunction } = await import('./module.js');
```

**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.

```javascript theme={"dark"}
// Importing a JSON module using the options argument
const config = await import('./config.json', { with: { type: 'json' } });
console.log(config.default.version);
```

**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.

```javascript theme={"dark"}
const version = 'v2';
const moduleName = 'parser';

// The specifier is computed at runtime
import(`./libs/${version}/${moduleName}.js`)
  .then((module) => module.init())
  .catch((err) => console.error(err));
```

**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.

```javascript theme={"dark"}
if (condition) {
  // Valid: Nested inside a block
  import('./feature.js').then(m => m.run());
}
```

## Static vs. Dynamic Import Comparison

| Characteristic           | Static `import`                                    | Dynamic `import()`                                |
| :----------------------- | :------------------------------------------------- | :------------------------------------------------ |
| **Resolution & Linking** | Pre-execution (Parse/Link phase)                   | Runtime                                           |
| **Evaluation Phase**     | Runtime (Strictly ordered before importing module) | Runtime (Upon expression execution)               |
| **Return Value**         | None (Declarative syntax)                          | `Promise<ModuleNamespaceObject>`                  |
| **Binding Mechanism**    | Live bindings                                      | Live bindings (via the resolved namespace object) |
| **Specifier**            | Strict string literal                              | Any expression evaluating to a string             |
| **Placement**            | Top-level only                                     | Anywhere (functions, blocks, etc.)                |
| **Environment**          | Modules only (`type="module"`)                     | Modules and standard Scripts                      |

## 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.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor JavaScript Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
