[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import/defer [Back]  [Original]

import.defer() - JavaScript | MDN

import.defer()

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The import.defer() syntax behaves like regular import() syntax, except that it results in a deferred module namespace object. The module and its dependencies are fetched and linked up front, but their synchronous evaluation is deferred until the namespace's properties are accessed.

For more information about deferred evaluation, including its interaction with top-level await, see the import defer declaration form.

In this article

Syntax

js
import.defer(moduleName)
import.defer(moduleName, options)

import.defer() is special syntax (a "meta property"), not a method on an import object.

Parameters

See import().

Return value

Returns a promise that fulfills with a deferred module namespace object after the module graph is loaded and linked, and any eagerly evaluated top-level await dependencies have finished evaluating.

Like regular import(), the promise rejects if the module or its dependencies cannot be loaded, parsed, or linked. It also rejects if an eagerly evaluated module throws. Errors from evaluation that remains deferred are instead thrown synchronously by the namespace operation that triggers evaluation.

Examples

Using import.defer()

Note: It's guaranteed that awaiting the resulting promise never accidentally calls an exported then methoda gotcha associated with the regular module namespace objectbecause the deferred module namespace object never exposes a property called then.

js
const ts = await import.defer("typescript");

function compilePath(path) {
  // Evaluation of the typescript module subgraph starts here
  const program = ts.createProgram([path], {});
}

Never immediately destructure the returned namespace, because it triggers evaluation:

js
const { createProgram } = await import.defer("typescript");
// The typescript module has now been evaluated.

Specifications

Specification
Deferred Imports Evaluation
# sec-left-hand-side-expressions

Browser compatibility

See also


Web Proxy Viewer  |  New URL  |  Original Page