Manually load a Go WebAssembly binary in a browser

Xiaoru Li
InstructorXiaoru Li

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

Go ^1.12

In this lesson, we will learn how to load and use a Go WebAssembly binary in a web app.

Instructor: [00:00] Here we have a precompiled Go Wasm binary to be loaded and executed on the client side in a browser. Before we start, let's create a dummy index.html page where we're going to load the Wasm binary into.

[00:15] In VS Code, the content of this file can be easily filled by using the amateur hand HTML:5. The first step is to copy the wasm_exec.js helper file from our Go installation into our project. Keep in mind that this file should be shipped together with our Wasm binary to the end users and should always be of the same version as the Go compiler that we use to compile the Wasm binary.

[00:46] Next, let's create a script tag in the header section of the HTML file to load the helper script and then make a new script section after that.

[00:56] Here we'll be calling the Go constructor function, which is exposed from the helper script to initialize the Go Wasm runtime. Then we'll use the WebAssembly.instantiateStreaming to fetch the Wasm binary that we want to load.

[01:13] This will return a Promise so we can channel callback and_then to execute the binary when the loading's complete by running go.run with result.instance. Alternatively, we can also run all this inside an async function using the async/await pattern to make it more readable. This piece of initializer code doesn't need to be changed very often.

[01:38] Now we can serve all these files using a local server to test the result. I'll be using the http-server npm module. We can see that our Wasm binary is successfully executed in a browser with the text "Hello, Egghead" correctly printed to the console.