gowebassemblygo-wasm

Loading brotli compressed WASM


I have a brotli compressed WASM file main.wasm.br. I have compressed this manually via CLI.

Currently in my HTML file I have below -

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>Go WASM</title>
    <script src="wasm_exec.js"></script>
    <script>
        const go = new Go();
        WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {
            go.run(result.instance);
        });
    </script>
</head>

<body></body>

</html>

This loads the uncompressed WASM file. If I change this to WebAssembly.instantiateStreaming(fetch("main.wasm.br"), go.importObject) I get below error -

Uncaught (in promise) TypeError: Failed to execute 'compile' on 'WebAssembly': Incorrect response MIME type. Expected 'application/wasm'.

How do I load this into my HTML?


Solution

  • Thanks everyone who commented and directed me towards the solution.

    So it simply boils down to understanding the basics of HTTP request/response -

    Content-Type controls what is the actual data type of response content.

    Content-Encoding controls what encoding/compression logic have we used to encode the response content.

    In my case, I manually compressed the wasm file using gzip and configured NginX as below -

    location ~ \.wasm {
        default_type 'application/wasm';
        add_header 'Content-Encoding' 'gzip';
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    }
    

    You can configure your makefile or build script to compress the wasm everytime you build the project.

    Note: I am yet to find a way to request brotli encoding and do similar config for brotli. By default, fetch requests with Accept-Encoding: deflate, gzip only. No brotli.