Skip to content
WebAssembly

Module Instantiation

Compile and instantiate a .wasm module.

By EZ4Code Team
instantiationcompilestreaming

Code

// Fetch and instantiate a WebAssembly module
const response = await fetch("module.wasm");
const bytes = await response.arrayBuffer();

// Async instantiation with imports
const { instance } = await WebAssembly.instantiate(bytes, {
  env: {
    log: (n) => console.log("wasm says:", n),
  },
});

console.log(instance.exports.add(2, 3));

// Streaming instantiation (compiles while downloading)
const { instance: inst2 } = await WebAssembly.instantiateStreaming(
  fetch("module.wasm"),
  { env: { log: console.log } }
);

Explanation

A WebAssembly module is compiled from bytes and instantiated with an imports object that supplies host functions. WebAssembly.instantiateStreaming compiles the response as it downloads, which is faster than buffering the whole file first. Exported functions become callable on instance.exports immediately after instantiation.

More WebAssembly Snippets