WebAssembly: Load a Module from JavaScript
WebAssembly loading is the process of fetching a .wasm file and turning it into a running instance. The standard path uses fetch with WebAssembly.instantiateStreaming.
The add module in WAT
This module exports one function named add. It takes two numbers and returns their sum.
(module
(func (export "add") (param i32 i32) (result i32)
local.get 0
local.get 1
i32.add))Load the module
Fetch the file. Pass the response to instantiateStreaming.
const response = await fetch("add.wasm");
const { instance } = await WebAssembly.instantiateStreaming(response);
console.log(instance.exports.add(2, 3));Load from bytes instead
Read the file into bytes first. Then pass the bytes to instantiate.
const response = await fetch("add.wasm");
const bytes = await response.arrayBuffer();
const { instance } = await WebAssembly.instantiate(bytes);
console.log(instance.exports.add(4, 5));Example
(async () => {
const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes);
console.log(instance.exports.add(2, 3));
console.log(instance.exports.add(10, 20));
})();Key points
- Instance: a running module, started from its bytes.
- Fetch downloads the .wasm file from the server.
- Use WebAssembly.instantiateStreaming to compile and start the module.
- InstantiateStreaming needs the correct MIME type from the server.
- The result holds an instance with the exported functions.
- Use instance.exports to call a function from the module.
In this example, the bytes are decoded from base64 and passed to WebAssembly.instantiate. The call returns an instance. Then the code calls the exported add function twice, first with 2 and 3, then with 10 and 20.
Note
A later lesson covers the MIME type in full detail.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which pair loads a .wasm file in the standard way?