Best Practices for WebAssembly using GoLang (1.15+)
Reducing the Binary File Size
In my last post, I showed you how to configure, develop, and generate a WASM file via GoLang. In this post, I will show you the best practices and how to use these strategies in a real modern web project.
Why Reduce the Binary File Size
If you already generate a web assembly binary file using Go, you’ve probably noticed how big the file size is. As we load this binary file on a web page, it will affect the load of other assets on the page. It can affect Time to Interactive (TTI) as well. TTI measures how long it takes a page to become fully interactive. A longer TTI can create a frustrating user experience, such as, the site appears to be ready, but when the user tries to interact with it, nothing happens.
I’ll show you two strategies to generate a smaller binary file size. The first one (recommended for most cases) is using gzip, and the other one is using a compiler called TinyGo.
Using gzip (recommended)
Gzip is a file format and software application used on Unix and Unix-like systems to compress HTTP content before it’s served to a client. We will use the gzip
command after compiling our Go file.
We are going to using this Go file (from my last post) as an example:
Compiling Our Go Code
Before we go all-in on the gzip compression, there’s something we can do to make binaries smaller: strip them.
We can use the -s and -w linker flags to strip the debugging information like this:
GOOS=js GOARCH=wasm go build -ldflags="-s -w" -o main.wasm
In this strategy, we will use the same Wasm JavaScript loader that we generated in my last post about WebAssembly:
$ cp “$(go env GOROOT)/misc/wasm/wasm_exec.js” .