2 ways to load and run a .wasm file in a browser:

  • the older WebAssembly.compile/WebAssembly.instantiate methods require you to create an ArrayBuffer containing your WebAssembly module binary after fetching the raw bytes, and then compile/instantiate it. This is analogous to new Function(string), except that we are substituting a string of characters (JavaScript source code) with an array buffer of bytes (WebAssembly source code).
  • the newer WebAssembly.compileStreaming/WebAssembly.instantiateStreaming methods are a lot more efficient — they perform their actions directly on the raw stream of bytes coming from the network, cutting out the need for the ArrayBuffer step

Older Way

for basic loading, there are three steps:

  • get the .wasm bytes into a typed array or ArrayBuffer
  • compile the bytes into a WebAssembly.Module
  • instantiate the WebAssembly.Module with imports to get the callable exports
fetch('module.wasm')
	.then(response => response.arrayBuffer())				     // get the .wasm bytes into a typed array or ArrayBuffer
	.then(bytes => WebAssembly.instantiate(bytes, importObject)) // compile & instantiate WebAssembly.Module
	.then(results => {
  		// Do something with the results!
	});

Newer Way

skips the ArrayBuffer step

fetch('simple.wasm')
	.then(bytes => WebAssembly.instantiateStreaming(bytes, importObject))
	.then(results => {
  		// Do something with the results!
	});

Example WebAssembly Object Function Calls

WebAssembly.instantiateStreaming(fetch('myModule.wasm'), importObject)
	.then(obj => {
  		// Call an exported function:
  		obj.instance.exports.exported_func();
 
  		// or access the buffer contents of an exported memory:
  		var i32 = new Uint32Array(obj.instance.exports.memory.buffer);
 
 		// or access the elements of an exported table:
 	 	var table = obj.instance.exports.table;
  		console.log(table.get(0)());
	})