principletypescriptTip
WebAssembly basics: compiling and loading WASM modules
Viewed 0 times
webassemblywasminstantiateStreaminglinear memorybinary formatcompile
browsernodejs
Error Messages
Problem
Understanding what WebAssembly is, when to use it, and the fundamental pattern for loading and calling a WASM module from JavaScript.
Solution
WASM is a binary instruction format that runs in a sandboxed VM in the browser or Node.js. Compile from C/C++/Rust. Load with WebAssembly.instantiateStreaming(fetch('module.wasm'), imports). Call exported functions directly.
Why
WASM runs at near-native speed for compute-intensive tasks (image processing, codecs, parsers, crypto). It is not faster than JS for DOM manipulation or async I/O.
Gotchas
- WASM modules must be served with Content-Type: application/wasm for streaming compilation
- WASM memory is a linear ArrayBuffer — passing strings/objects requires explicit marshaling
- Synchronous instantiation (WebAssembly.instantiate with buffer) is slower than streaming
- WASM cannot access the DOM directly; all DOM interaction goes through JS
Code Snippets
Loading a WASM module
const { instance } = await WebAssembly.instantiateStreaming(
fetch('/module.wasm'),
{ env: { memory: new WebAssembly.Memory({ initial: 256 }) } }
);
const result = (instance.exports.add as Function)(1, 2);Revisions (0)
No revisions yet.