Using the streaming WebAssembly APIs

The most efficient way to fetch, compile and instantiate a WebAssembly module is to use the streaming variants of the WebAssembly API. For example, you can use instantiateStreaming combined with fetch to perform all three steps in one go:

  1. const { instance, module } = await WebAssembly.instantiateStreaming(
  2. fetch("https://wpt.live/wasm/incrementer.wasm"),
  3. );
  4. const increment = instance.exports.increment as (input: number) => number;
  5. console.log(increment(41));

Note that the .wasm file must be served with the application/wasm MIME type. If you want to do additional work on the module before instantiation you can instead use compileStreaming:

  1. const module = await WebAssembly.compileStreaming(
  2. fetch("https://wpt.live/wasm/incrementer.wasm"),
  3. );
  4. /* do some more stuff */
  5. const instance = await WebAssembly.instantiate(module);
  6. instance.exports.increment as (input: number) => number;

If for some reason you cannot make use of the streaming methods you can fall back to the less efficient compile and instantiate methods. See for example the MDN docs. For a more in-depth look on what makes the streaming methods more performant, see for example this post.