WebAssembly.fr/en/

Using Wasm in a Web page

Demo of loading wasm to use in a html page on a website.

Using two mathematical functions, mult() and fact(), as examples.

Preparing the hosting environment

In the .htaccess file at the root of your site, add the following line:

AddType application/wasm .wasm

Alternatively, look for an equivalent instruction in your hosting provider's or server's documentation.

C++ code

This very simple code contains two calculation functions: one for multiplication and one for calculating a factorial.

extern "C" double fact(int i) {
 long long n = 1;
 for (;i > 0; i--) {
 n *= i;
 }
 return (double) n;
} 

extern "C" int mult(int a, int b) {
    return a * b;
}

The C++ compiler included in Emscripten modifies function names and other references during compilation (mangling). However, this does not apply to functions marked with extern "C"; adding this prefix allows you to use the original C++ source names fact and mult within your JavaScript code.

Compilation command

You must have Emscripten installed to convert C++ code into WebAssembly.

emcc test.cpp -O3 -s STANDALONE_WASM=1 -Wl,--export=mult -Wl,--export=fact -Wl,--no-entry -o test.wasm

The STANDALONE_WASM option indicates that the module is self-contained and does not require external code.

The -Wl options are used to export the identifiers.

--no-entry allows the code to be used as a library of functions rather than as a standalone program (which is appropriate for this type of use case).

JavaScript code

The WebAssembly module is loaded using the `fetch` method and then converted via the instantiateStreaming method of the browser's built-in WebAssembly object.

<script type="module">
 window.init = async function() {
    const { instance } = await WebAssembly.instantiateStreaming(
        fetch("./test.wasm").then(r => {
            for (const [k,v] of r.headers.entries())
                console.log(k, "=", v);
            return r;
          }
        ) // then
    ) //instanciate
    let mult = instance.exports.mult
    document.getElementById("result").innerHTML = "Multiply 10x55: " + mult(10,55);
    let fact = instance.exports.fact;
    document.getElementById("result").innerHTML += "\nFactor 6: " + fact(6);
};

window.addEventListener("load", init);
</script>

It is essential to wait for the page to load before calling init(), which executes asynchronously.

The mult and fact functions from the module are assigned to JavaScript identifiers that invoke them and display the results on the page.

Demonstration