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, importObject)
Parameters
source-
A
Responseobject or a promise that will fulfill with one, representing the underlying source of a Wasm module you want to stream, compile, and instantiate. importObjectOptional-
An object containing the values to be imported into the newly-created
Instance, such as functions orWebAssembly.Memoryobjects. There must be one matching property for each declared import of the compiled module or else aWebAssembly.LinkErroris thrown.
Return value
A Promise that resolves to a ResultObject which contains two
fields:
-
module: AWebAssembly.Moduleobject representing the compiled WebAssembly module. ThisModulecan be instantiated again or shared via postMessage(). -
instance: AWebAssembly.Instanceobject that contains all the Exported WebAssembly functions.
Exceptions
-
If either of the parameters are not of the correct type or structure, a
TypeErroris thrown. -
If the operation fails, the promise rejects with a
WebAssembly.CompileError,WebAssembly.LinkError, orWebAssembly.RuntimeError, depending on the cause of the failure.
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.
Specifications
| Specification |
|---|
| WebAssembly Web API # dom-webassembly-instantiatestreaming |
Browser compatibility
BCD tables only load in the browser