Load and Run Go WebAssembly Module
When I tried to write and run my first Go WebAssembly module, it seemed to be a easy task. I searched load wasm module that led me to the tutorial on MDN [1]. It looks easy, just use WebAssembly.instantiateStreaming() method and everything is done. But life is not so easy. It did not work. So I took a look at what other people did in their first Go wasm try (see references in [2]) and found out the solution.
To load and run compiled Go wasm module, we need a JavaScript loader provided in Go source. We can copy the JavaScript loader to current directory by the following shell command:
$ cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .
You can also download wasm_exec.js from Go GitHub repo.
Next, put wasm_exec.js, compiled Go wasm module (assume the name of the module is mymodule.wasm) and HTML file in the same directory. Insert the following code in the HTML file.
<script src="wasm_exec.js"></script>
<script>
const go = new Go();
let mod, inst;
WebAssembly.instantiateStreaming(
fetch("mymodule.wasm", {cache: 'no-cache'}), go.importObject).then((result) => {
mod = result.module;
inst = result.instance;
run();
});
async function run() {
await go.run(inst);
};
</script>
Open the HTML with your browser and now you will see Go wasm code loaded and running!
Tested on:
- Ubuntu Linux 18.04
- Go 1.11.1
- Chromium Version 69.0.3497.81 on Ubuntu 18.04 (64-bit)
References:
[1] | Loading and running WebAssembly code - WebAssembly | MDN |
[2] | [Go WebAssembly] First Wasm Program - Hello World |
[3] | WebAssembly · golang/go Wiki · GitHub |