The WebAssembly.instantiateStreaming() function compiles and instantiates a WebAssembly module directly from a streamed underlying source. This is the most efficient, optimized way to load wasm code.
The WebAssembly.instantiateStreaming() function compiles and instantiates a WebAssembly module directly from a streamed underlying source. This is the most efficient, optimized way to load wasm code.
WebAssembly.instantiateStreaming(source, importObject)
source A Response object or a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream, compile, and instantiate.
importObject Optional
An object containing the values to be imported into the newly-created Instance, such as functions or WebAssembly.Memory objects. There must be one matching property for each declared import of the compiled module or else a WebAssembly.LinkError is thrown.
A Promise that resolves to a ResultObject which contains two fields:
module: A WebAssembly.Module object representing the compiled WebAssembly module. This Module can be instantiated again or shared via postMessage(). instance: A WebAssembly.Instance object that contains all the Exported WebAssembly functions. TypeError is thrown. WebAssembly.CompileError, WebAssembly.LinkError, or WebAssembly.RuntimeError, depending on the cause of the failure. 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 = { imports: { 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.
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js | |
instantiateStreaming |
61 |
16 |
58 |
No |
47 |
15 |
61 |
61 |
58 |
45 |
15 |
8.0 |
1.12 |
No |
© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming