6

Load and Run Go WebAssembly Module

 2 years ago
source link: http://siongui.github.io/2018/10/06/load-and-run-golang-wasm-code/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Load and Run Go WebAssembly Module

October 06, 2018

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:

[3]WebAssembly · golang/go Wiki · GitHub


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK