DEV Community

loading...

Web Workers - Introduction

pmkroeker profile image Peter ・2 min read

Some pre-reading if you wish!

After reading the above post I started thinking more about web workers. Why are more people not talking about them. So many people seem to be worried about performance, so why is the worker discussion not more prevalent?

The MDN Docs for workers are quite extensive, discussing every aspect from API Specs to usage.

My initial reasoning for not using them was that I did not think that there really was a need for them. Second, the initialization methodology

const worker = new Worker('/path/to/worker.js')

does not jive nicely with a full TypeScript environment. To use the base call method, you would need to create a separate worker.ts file to transpile over, and it would need to be in the correct location for the final application (which may be quite different from where app src is). I found this frustrating, so I decided at the time to not bother with them.

Then I saw this post from Surma, and I started thinking more about them again. With a data vis dashboard as our primary app, we could definitely benefit from moving calculations from the main thread into a worker.

So I started looking through some of the worker wrappers mentioned the above post (Comlink & Workerize). I started with workerize, then quickly decided I wanted a more in depth approach with multiple methods, so I settled on using Comlink! Using webpack, I also found webpack worker-loader.

Comlink does a good job at making you feel like working with your worker is working with a class. Methods are easy to use, and setup is pretty straight forward! If you are on the fence about adding workers to your app, I would suggest taking a look at Comlink, it makes the process of using a worker way easier, and pairing it with worker-loader takes the awkwardness of defining things as workers away.

The next post in the Workers series will be about my implementation!

Discussion

pic
Editor guide