Manually load a Go WebAssembly binary in a browser

Xiaoru Li
InstructorXiaoru Li
Share this video with your friends

Social Share Links

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.

egghead
egghead
~ 6 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today