WebAssembly

There are currently two major differences to take into account when using WebAssembly opposed to asm.js. First, extra steps must be taken to initialize its Module and only some browsers support WebAssembly.

Initializing the Module

modules.rs provides a complete example of initializing a WebAssembly library produced by the Rust compiler. The relevant code is provided below for convenience:

import $ from "jquery";

export let WasmModule = false;

const wasm_path = "path/to/webassembly_library.wasm";
const js_path = "path/to/module.js";

export const load_wasm_module = () => (
    new Promise((resolve, reject) => {
        /* Load the WebAssembly. */
        fetch(wasm_path).then((response) => {
            if (response.ok) {
                /* module.js expects to find a global variable called WasmModule. */
                window.WasmModule = {};
                return response.arrayBuffer();
            } else {
                throw "Unable to load wasm module!";
            }
        }).then((buffer) => {
            /* Assign the WasmModule's wasmBinary to be the loaded WebAssembly. */
            window.WasmModule.wasmBinary = buffer;
            /* Load the JavaScript that references the WasmModule. */
            return $.getScript(js_path);
        }).then(() => {
            WasmModule = window.WasmModule;
            resolve();
        }).catch((err) => {
            console.error(err);
            reject();
        });
    })
);

/* Detect if the browser has native WebAssembly support. */
export const native_support = () => ("WebAssembly" in window);

This is certainly not the simplest way to initialize a library. However, this is a known pain point and there is work to improve it.

Ok, so what is going on? Essentially, we care about two of the files Cargo produces when we target WebAssembly: target/wasm32-unknown-emscripten/release/deps/{project_name}-{some-hash}.wasm and target/wasm32-unknown-emscripten/release/{project_name}.js. The first file is our WebAssembly library and the second file exposes the Module API we have been using to interact with our library. However, before we can load the Module file we must first load the WebAssembly and assign it to our Module's wasmBinary field.

Supported Browsers

Browsers which currently support WebAssembly are Firefox Nightly (not beta), Chrome Canary (Windows, Android, and OSX only), and the raw build of Chromium.

results matching ""

    No results matching ""