TIL: Web Workers

Last updated: Sun Apr 30 2023

I’ve got a search page, using Fuse.js to do searching on the client-side. I wanted to move it to a background thread to improve performance, since searches are sometimes slow enough to block interaction on the main thread. The Web Workers API seems to be the standard way to do that.

Luckily, that was pretty straightforward! I implemented search-worker.ts, which listens for messages via onmessage, calls the Fuse API to retrieve results given a query, and returns those results to the main page via postMessage. The main search component sends the current query via postMessage. And… that’s about it! Search still works, now without blocking the main thread.

The one tricky part was getting this to build in Astro, which uses Vite for compilation. That required a quick trip to the Vite docs, which explains that I have to create a Worker like so:

new Worker(new URL("../search-worker", import.meta.url), {
    type: "module",
});

As long as search-worker.ts is in the src/ directory and not the public/ directory, Vite will compile and bundle this correctly.

References