WebAssembly Polyfill (prototype)
This repo contains a prototype built to demonstrate the viability of a WebAssembly polyfill. Work is ongoing in other repos to design the actual standard binary format. This prototype also makes no attempt to call native browser decoding and so it is not, technically, a polyfill but rather a pure JS library.
See FAQ entry.
How it (currently) works
A real (non-prototype) polyfill would hook into an ES6 Module loader polyfill so that loading a WebAssembly module will Just Work. The scheme described here is just a proof of concept for how the polyfill can avoid massive copying, string manipulation and garbage.
- On the main thread, the client kicks off a load of a URL by calling
loadWebAssemblyand receives a
- The polyfill library starts up a worker containing asm.js code compiled from
unpack.cppconcatenated with the glue code in
- The worker glue code fetches the binary via XHR then copies the result into the asm.js heap.
- The asm.js code decodes the binary into asm.js in the form of UTF8 bytes in a separate region of the asm.js heap.
- The worker glue code creates a
Blob(a read-only copy) from a view of just the asm.js UTF8 bytes.
postMessage()ed back to the main thread (a non-copying operation) where it is loaded as a script element with
script.src = URL.getObjectURL(blob).
- When the asm.js script is executed, it passes the asm.js module function object to a callback which resolves the promise in step 1.
The library in
jslib/ should be ready to use, just copy both files and call
make compiles the C++ implementation into the JS files in
into native executables in
tools/. (The Makefile is currently super-unportable.
Sorry! Patches welcome.)
Packing asm.js into the binary format
The polyfill also comes with a tool (
tools/pack-asmjs) that compiles a single JS
file (containing only asm.js) into the (experimental) WebAssembly format decoded by
the library. Given an existing asm.js application, one can experiment with this
polyfill (perform direct size/load-time comparisons) by following the steps:
- Separate the asm.js module out into a separate file.
tools/pack-asmjsto produce a
- Refactor the code that called the asm.js module to instead call
loadWebAssembly()(which returns a promise that resolves to the unlinked asm.js module function).
- Decode while downloading (using HTTP
Rangerequests or splitting into separate files)
- Perform generic compression on top of the
.wasmfile (e.g., lzham gives a further 24% boost over