Web Workers with Comlink

On my site footylivescores.com we make lots of api calls to retrieve data, this is an ideal use case for a web worker, we can free up the UI thread.

“Web Workers are a simple means for web content to run scripts in background threads”

Workers are ideal for any slow or intensive process we need to run which allows us to keep the UI thread free to handle user input. Workers can make api calls and even access browser storage, but obviously cannot manipulate the dom.

To create a worker we call Worker passing a path to our worker script create worker

I am using sveltekit and vite which requires a little extra work, we need to append worker to the script path when importing, this allows us to use import in our worker rather than importScripts. create worker sveltekit

Workers use postMessage to send messages to and from a worker, and the on message event to receive messages postMessage

This works fine but there is a nicer way, comlink abstracts the messaging pattern into RPC, making it easier to communicate with workers. comlink expose

My worker now looks like this, Comlink.expose allows you to expose objects, functions and properties with the message handling. All I need to do now is wrap my worker object and I can access my worker like it is an ordinary object. comlink wrap

© 2024 Timney.