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. );
5. const increment = instance.exports.increment as (input: number) => number;
6. 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. );
5. /* do some more stuff */
7. const instance = await WebAssembly.instantiate(module);
8. 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.
