2 ways to load and run a .wasm file in a browser:
- the older
WebAssembly.compile/WebAssembly.instantiatemethods require you to create anArrayBuffercontaining your WebAssembly module binary after fetching the raw bytes, and then compile/instantiate it. This is analogous tonew Function(string), except that we are substituting a string of characters (JavaScript source code) with an array buffer of bytes (WebAssembly source code). - the newer
WebAssembly.compileStreaming/WebAssembly.instantiateStreamingmethods are a lot more efficient — they perform their actions directly on the raw stream of bytes coming from the network, cutting out the need for theArrayBufferstep
Older Way
for basic loading, there are three steps:
- get the
.wasmbytes into a typed array orArrayBuffer - compile the bytes into a
WebAssembly.Module - instantiate the
WebAssembly.Modulewith imports to get the callable exports
fetch('module.wasm')
.then(response => response.arrayBuffer()) // get the .wasm bytes into a typed array or ArrayBuffer
.then(bytes => WebAssembly.instantiate(bytes, importObject)) // compile & instantiate WebAssembly.Module
.then(results => {
// Do something with the results!
});Newer Way
skips the ArrayBuffer step
fetch('simple.wasm')
.then(bytes => WebAssembly.instantiateStreaming(bytes, importObject))
.then(results => {
// Do something with the results!
});Example WebAssembly Object Function Calls
WebAssembly.instantiateStreaming(fetch('myModule.wasm'), importObject)
.then(obj => {
// Call an exported function:
obj.instance.exports.exported_func();
// or access the buffer contents of an exported memory:
var i32 = new Uint32Array(obj.instance.exports.memory.buffer);
// or access the elements of an exported table:
var table = obj.instance.exports.table;
console.log(table.get(0)());
})