Wasm in Web Worker

View full source code

A simple example of parallel execution by spawning a web worker with web_sys, loading Wasm code in the web worker and interacting between the main thread and the worker.

Building & compatibility

At the time of this writing, only Chrome supports modules in web workers, e.g. Firefox does not. To have compatibility across browsers, the whole example is set up without relying on ES modules as target. Therefore we have to build with --target no-modules. The full command can be found in build.sh.


The Cargo.toml enables features necessary to work with the DOM, log output to the JS console, creating a worker and reacting to message events.

name = "wasm-in-web-worker"
version = "0.1.0"
authors = ["The wasm-bindgen Developers"]
edition = "2018"
rust-version = "1.57"

crate-type = ["cdylib"]

wasm-bindgen = "0.2.92"
console_error_panic_hook = { version = "0.1.6", optional = true }

version = "0.3.4"
features = [


Creates a struct NumberEval with methods to act as stateful object in the worker and function startup to be launched in the main thread. Also includes internal helper functions setup_input_oninput_callback to attach a wasm_bindgen::Closure as callback to the oninput event of the input field and get_on_msg_callback to create a wasm_bindgen::Closure which is triggered when the worker returns a message.

# #![allow(unused_variables)]
#fn main() {
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use web_sys::{console, HtmlElement, HtmlInputElement, MessageEvent, Worker};

/// A number evaluation struct
/// This struct will be the main object which responds to messages passed to the
/// worker. It stores the last number which it was passed to have a state. The
/// statefulness is not is not required in this example but should show how
/// larger, more complex scenarios with statefulness can be set up.
pub struct NumberEval {
    number: i32,

impl NumberEval {
    /// Create new instance.
    pub fn new() -> NumberEval {
        NumberEval { number: 0 }

    /// Check if a number is even and store it as last processed number.
    /// # Arguments
    /// * `number` - The number to be checked for being even/odd.
    pub fn is_even(&mut self, number: i32) -> bool {
        self.number = number;
        self.number % 2 == 0

    /// Get last number that was checked - this method is added to work with
    /// statefulness.
    pub fn get_last_number(&self) -> i32 {

/// Run entry point for the main thread.
pub fn startup() {
    // Here, we create our worker. In a larger app, multiple callbacks should be
    // able to interact with the code in the worker. Therefore, we wrap it in
    // `Rc<RefCell>` following the interior mutability pattern. Here, it would
    // not be needed but we include the wrapping anyway as example.
    let worker_handle = Rc::new(RefCell::new(Worker::new("./worker.js").unwrap()));
    console::log_1(&"Created a new worker from within Wasm".into());

    // Pass the worker to the function which sets up the `oninput` callback.

fn setup_input_oninput_callback(worker: Rc<RefCell<web_sys::Worker>>) {
    let document = web_sys::window().unwrap().document().unwrap();

    // If our `onmessage` callback should stay valid after exiting from the
    // `oninput` closure scope, we need to either forget it (so it is not
    // destroyed) or store it somewhere. To avoid leaking memory every time we
    // want to receive a response from the worker, we move a handle into the
    // `oninput` closure to which we will always attach the last `onmessage`
    // callback. The initial value will not be used and we silence the warning.
    let mut persistent_callback_handle = get_on_msg_callback();

    let callback = Closure::new(move || {
        console::log_1(&"oninput callback triggered".into());
        let document = web_sys::window().unwrap().document().unwrap();

        let input_field = document
            .expect("#inputNumber should exist");
        let input_field = input_field
            .expect("#inputNumber should be a HtmlInputElement");

        // If the value in the field can be parsed to a `i32`, send it to the
        // worker. Otherwise clear the result field.
        match input_field.value().parse::<i32>() {
            Ok(number) => {
                // Access worker behind shared handle, following the interior
                // mutability pattern.
                let worker_handle = &*worker.borrow();
                let _ = worker_handle.post_message(&number.into());
                persistent_callback_handle = get_on_msg_callback();

                // Since the worker returns the message asynchronously, we
                // attach a callback to be triggered when the worker returns.
            Err(_) => {
                    .expect("#resultField should exist")
                    .expect("#resultField should be a HtmlInputElement")

    // Attach the closure as `oninput` callback to the input field.
        .expect("#inputNumber should exist")
        .expect("#inputNumber should be a HtmlInputElement")

    // Leaks memory.

/// Create a closure to act on the message returned by the worker
fn get_on_msg_callback() -> Closure<dyn FnMut(MessageEvent)> {
    Closure::new(move |event: MessageEvent| {
        console::log_2(&"Received response: ".into(), &event.data());

        let result = match event.data().as_bool().unwrap() {
            true => "even",
            false => "odd",

        let document = web_sys::window().unwrap().document().unwrap();
            .expect("#resultField should exist")
            .expect("#resultField should be a HtmlInputElement")



Includes the input element #inputNumber to type a number into and a HTML element #resultField were the result of the evaluation even/odd is written to. Since we require to build with --target no-modules to be able to load Wasm code in in the worker across browsers, the index.html also includes loading both wasm_in_web_worker.js and index.js.


    <meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
    <link rel="stylesheet" href="style.css">

    <div id="wrapper">
        <h1>Main Thread/Wasm Web Worker Interaction</h1>

        <input type="text" id="inputNumber">

        <div id="resultField"></div>

    <!-- Make `wasm_bindgen` available for `index.js` -->
    <script src='./pkg/wasm_in_web_worker.js'></script>
    <!-- Note that there is no `type="module"` in the script tag -->
    <script src="./index.js"></script>




Loads our Wasm file asynchronously and calls the entry point startup of the main thread which will create a worker.

// We only need `startup` here which is the main entry point
// In theory, we could also use all other functions/struct types from Rust which we have bound with
// `#[wasm_bindgen]`
const {startup} = wasm_bindgen;

async function run_wasm() {
    // Load the wasm file by awaiting the Promise returned by `wasm_bindgen`
    // `wasm_bindgen` was imported in `index.html`
    await wasm_bindgen();

    console.log('index.js loaded');

    // Run main Wasm entry point
    // This will create a worker from within our Rust code compiled to Wasm



Loads our Wasm file by first importing wasm_bindgen via importScripts('./pkg/wasm_in_web_worker.js') and then awaiting the Promise returned by wasm_bindgen(...). Creates a new object to do the background calculation and bind a method of the object to the onmessage callback of the worker.

// The worker has its own scope and no direct access to functions/objects of the
// global scope. We import the generated JS file to make `wasm_bindgen`
// available which we need to initialize our Wasm code.

console.log('Initializing worker')

// In the worker, we have a different struct that we want to use as in
// `index.js`.
const {NumberEval} = wasm_bindgen;

async function init_wasm_in_worker() {
    // Load the wasm file by awaiting the Promise returned by `wasm_bindgen`.
    await wasm_bindgen('./pkg/wasm_in_web_worker_bg.wasm');

    // Create a new object of the `NumberEval` struct.
    var num_eval = NumberEval.new();

    // Set callback to handle messages passed to the worker.
    self.onmessage = async event => {
        // By using methods of a struct as reaction to messages passed to the
        // worker, we can preserve our state between messages.
        var worker_result = num_eval.is_even(event.data);

        // Send response back to be handled by callback in main thread.