An early look at WebAssembly
published: 05 August 2016
reading time: 10 mins
Keeping on the cutting edge of frontend technology can feel like you're trying to herd cats at times. The huge choice of tooling, libraries and frameworks has simultaneously improved the developer experience and caused a lot of buzz about 'fatigue' and 'churn' with people trying to keep up. In this post I'm going to take a look at what may significantly change how we develop webpages in the future and become The Next Big Thing™: WebAssembly.
This is where WebAssembly comes in.
WebAssembly is a specification for a native bytecode compile target. The idea is that you can compile the language of your choice directly to a WebAssembly executable and have it run as true native code. This is great news for people wanting to do 3D rendering, compression or anything performance intensive directly on the web.
Currently, the only way to produce a WebAssembly binary is from a piece of asm.js source. We could use Emscripten to do this, but let's keep it simple and write our own;
This should be fairly familiar. Anyone used to writing in strict mode will recognise the prologue directive for notifying the browser to treat this code as asm.js. The bitfield OR zero operation is used in asm.js to denote integers.
Next we need to download a copy of the WebAssembly toolchain Binaryen and compile it. After compiling, we can use the asm2wasm tool to produce a human-readable representation of the WebAssembly bytecode in the current S-Expression format.
Lisp programmers will probably feel quite at home looking at this syntax. For everyone else, you're looking at a tree representation of the abstract syntactic structure of WebAssembly bytecode. From here, we can use wasm-as to produce our final binary;
Now we finally have a web executable! Unfortunately...
After playing around trying to enable the experimental WebAssembly support in Chromium it just won't run for me, even after manually hex editing the binary to try and conform to whatever implementation I have installed.
Being so early in the development timeline of WebAssembly I kind of expected this to happen. Not put off, I decided to try the latest nightly of Chrome Canary.
Hurrah! Finally running native code on the web. I must have been using a more recent version of Binaryen than that is implemented in Chromium. Enabling WebAssembly support exposes a `Wasm` global variable and you can use its instantiateModule method to load your custom WebAssembly binary.
It's very early days for WebAssembly at the moment. Expect support to gradually improve and the intermediate asm.js step to be phased out as tooling develops.
Further information including a roadmap can be found at GitHub.