Comprehensive documentation of WebAssembly APIs, module instantiation, and memory management.
Start ExploringWebAssembly APIs provide low-level access to WebAssembly modules within the browser. These APIs enable JavaScript to load, instantiate, and interact with WebAssembly modules, offering high-performance execution of binary code.
WebAssembly modules require explicit memory management through WebAssembly.Memory
instances. Memory is allocated as contiguous byte arrays and exported from modules.
// Load and run the WebAssembly module
fetch('fast-algorithm.wasm')
.then(response => response.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes, {
env: {
memory: new WebAssembly.Memory({ initial: 256 }),
table: new WebAssembly.Table({ initial: 20, element: 'anyfunc' })
}
}))
.then(results => {
const exportedFunctions = results.instance.exports;
let result = exportedFunctions.complexCalculation(42);
console.log('Result:', result);
});
Memory Management Example:
new WebAssembly.Memory({ initial: 256 })
Memory.buffer
The WebAssembly.Module
class compiles a WebAssembly module, which contains the code of a WebAssembly function.
WebAssembly.compile(buffer)
The WebAssembly.Instance
class represents an instance of a WebAssembly module.
WebAssembly.instantiate(module, imports)
Memory objects provide shared linear memory between JavaScript and WebAssembly. Memory is created with an initial size and can grow as needed.
new WebAssembly.Memory({ initial: 256, maximum: 1024 })
Follow these steps to integrate WebAssembly into your web application. We'll use Rust as an example, but similar workflows apply to C/C++ and AssemblyScript.
// lib.rs
#[no_mangle]
pub extern "C" fnn fastCalc(input: i32) -> i32 {
input * input + 42
}
// YourJavaScript.js
WebAsembly.instantiateStreaming(fetch('fast-calc.wasm'), {
env: {
memory: new WebAsembly.Memory({ initial: 256 })
}
})
.then(results => {
let result = results.instance.exports.fastCalc(42);
console.log(result); // 1764 + 42 = 1806
});
Use Memory.buffer
to access shared memory between JavaScript and WebAssembly.
const jsArray = new Uint32Array(memory.buffer); jsArray[0] = 42; const wasmResult = module.exports.getResult(0); console.log(wasmResult); // 42
WebAssembly Table objects allow storage of function references. These can be used to implement complex control flow or callback systems.
new WebAsembly.Table({ initial: 10, element: 'anyfunc' })
WebAssembly supports streaming compilation which allows faster startup times by compiling as the bytes arrive.
WebAsembly.compileStreaming(fetch('huge-module.wasm'))