docs.rodeo

MDN Web Docs mirror

WebAssembly.instantiateStreaming()

The WebAssembly.instantiateStreaming() static method compiles and instantiates a WebAssembly module directly from a streamed underlying source. This is the most efficient, optimized way to load Wasm code.

[!NOTE] Webpages that have strict Content Security Policy (CSP) might block WebAssembly from compiling and executing modules. For more information on allowing WebAssembly compilation and execution, see the script-src CSP.

Syntax

WebAssembly.instantiateStreaming(source)
WebAssembly.instantiateStreaming(source, importObject)
WebAssembly.instantiateStreaming(source, importObject, compileOptions)

Parameters

Return value

A Promise that resolves to a ResultObject which contains two fields:

Exceptions

Examples

Instantiating streaming

The following example (see our instantiate-streaming.html demo on GitHub, and view it live also) directly streams a Wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a ResultObject. Because the instantiateStreaming() function accepts a promise for a Response object, you can directly pass it a fetch() call, and it will pass the response into the function when it fulfills.

const importObject = {
  my_namespace: { imported_func: (arg) => console.log(arg) },
};

WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
  (obj) => obj.instance.exports.exported_func(),
);

The ResultObject’s instance member is then accessed, and the contained exported function invoked.

[!NOTE] For this to work, .wasm files should be returned with an application/wasm MIME type by the server.

Enabling JavaScript builtins and global string imports

This example enables JavaScript string builtins and imported global string constants when compiling and instantiating the Wasm module with instantiateStreaming(), before running the exported main() function (which logs "hello world!" to the console). See it running live.

const importObject = {
  // Regular import
  m: {
    log: console.log,
  },
};

const compileOptions = {
  builtins: ["js-string"], // Enable JavaScript string builtins
  importedStringConstants: "string_constants", // Enable imported global string constants
};

WebAssembly.instantiateStreaming(
  fetch("log-concat.wasm"),
  importObject,
  compileOptions,
).then((result) => result.instance.exports.main());

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN