Lesson 2 of 9 · 18m
Loading and Instantiating Modules
WebAssembly.compileStreaming, instantiate, imports and exports, caching, MIME types, and the operational details that make loading boring instead of fragile.
Every production Wasm bug I've been called into eventually lands in the loader: wrong MIME type, compiling on the main thread during startup, instantiating repeatedly, or shipping a hand-rolled fallback that behaves differently in every browser. Loading is simple, but only if you understand exactly what the API is doing.
Compile once, instantiate as needed
const modulePromise = WebAssembly.compileStreaming(fetch("/kernels/image.wasm"));
const module = await modulePromise;
const instance = await WebAssembly.instantiate(module, imports);
console.log(instance.exports); // exported functions, memory, tables, globalscompile validates and compiles bytes into a reusable WebAssembly.Module. instantiate creates a running instance with its own memory and state. Most applications want one compile and few instantiations. Recompiling the same bytes in a loop is pure waste.
compileStreaming is preferred because the engine can compile while bytes arrive. It requires the response to be served as application/wasm; otherwise browsers reject it in some contexts. On nginx that means:
types {
application/wasm wasm;
}Imports are capabilities
The second argument to instantiate is the import object. This is how the host grants capabilities:
const imports = {
env: {
memory: new WebAssembly.Memory({ initial: 16, maximum: 256 }),
log_u32(value) { console.log("wasm says", value); },
now() { return performance.now(); },
},
};Import names are not magic. They must exactly match what the compiled module expects, including module namespace (env is a convention, not a standard). If instantiation fails with a missing import error, the compiler toolchain's generated glue or documentation is the source of truth — don't guess.
Load in the background, not at interaction time
Compile during application startup in parallel with other work, often inside a worker. Do not compile the first time a user clicks a button unless the feature is truly rare. For large modules, compile in a worker and transfer bytes or use a compile cache strategy appropriate to the app.
Field notes
WebAssembly.instantiateStreamingcombines compile and instantiate, but separate compile is clearer when multiple instances or workers share code.- A wrong MIME type is an operational failure, not a JavaScript failure. Fix the server config.
- Never assume
instance.exports.memoryexists; some toolchains import memory instead of exporting it. - Put loader failures behind a typed error message. 'missing import env.log_u32' is actionable; 'wasm failed' is not.
Was this lesson helpful?