Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Load a WebAssembly Function Written in Rust and Invoke it from JavaScript


    In this lesson we are going to setup a project from scratch by introducing the JavaScript snippet to load a WebAssembly module. We demonstrate two different ways and showcase the benefit of the streaming solution. Once the module is loaded we can invoke a function previously exported from our Rust code.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: Use Cargo.new to create a new project called utils. Use --lib to declare that it's going to be a library. Next, we need to change the create type to cdylib in Cargo.toml. This has an impact on how things are linked together during compilation.

    We're now ready to write our first lines of Rust code. Let's get right into it, and create a public function, addOne. The extern keyword is needed to create an interface so that this function can be invoked from other languages.

    The function accepts a value X, which is an unsigned integer, which is incremented by one and returned. In addition, we need to add a @nomangle annotation to tell the Rust compiler not to mangle the name of this function.

    Next up, we can use Cargo.build to compile our utils library, targeting WebAssembly. After that, we can run wasm.gc, and output it to utils.gc.wasm in the current directory. Next up, we need to load it somehow. Therefore, we're going to create an index.html file and open a script tag.

    To load a WebAssembly module, we can fetch it, convert the response to an array buffer, instantiate the result, and then use the WASM module. It has an instance with export, including our addOne function. We can invoke the function and append the result to the DOM.

    Let's give this a try. We start our web server running HTTP. Once we open a site in the browser, we can see the result. Awesome. Here, you can see that our addOne function printed out the result of adding two plus one.

    There is one more improvement, though. In the current implementation, we fetch the entire WASM file before we instantiate it. Using instantiate streaming instead, we can stream, compile, and instantiate a WebAssembly module in one go.

    Especially on slow connections, this can speed up the time to execution a lot. We reload and review the result. Worked like a charm. Be aware, instantiate streaming requires that our WASM file must be served through the content type, application/wasm. Fortunately, our HTTP server already does so.