Why Web Workers?

April 09, 2018 0 Comments

Why Web Workers?



Published Apr 08, 2018Last updated Apr 09, 2018

Why Web Workers?

Web Workers appeared about eight years ago but we still don't mention it much in the front-end scence.

What is Web Worker?

A Web Worker is a process that executes code separately from the main thread. It has no access to the DOM but can perform most of the non-UI related tasks. Everything happening inside the worker does not affect the UI thread.

Why is it important?

One word: Performance.
Front-end code tends to handle more and more resource-intensive tasks. Yet we still want the UI to run smoothly: 60 fps for most devices. In other words the app gets 16 milliseconds to run the JavaScript code and render the DOM again.


  • JavaScript is single threaded: it can only execute one line of code at a time.
  • The browser only allocates a certain amount of resources to a tab - our main thread.
  • More apps offer offline capabilities requiring a lot of processing on the device itself.

Delegating non-UI work to other threads than the UI helps us meet our 16 ms budget. The worker processes the data and sends back the result to the main thread.


We have our app that filters and sorts a large data set (ex. 7000 records) with some fancy animations running. We filter the list as we type in the search box.
Filtering an array of 7000+ objects is no big deal for your developer's workstation. But on your smartphone the app will be janky.

But why?
Each time the user types in, the app filters the list then renders. Meanwhile the user cannot type, the UI freeze. The filtering itself takes over 16 ms: we're (way) over the budget.

Enter the Web Worker
Delegating that task to the worker does two things. First, the UI is not blocked while the worker filters the data. Then the results are returned a bit faster as we have allocated more resources.

Going Further

Our app is not janky anymore but still takes quite some time to return the results. To solve this we can use even more resources: let's spawn a dozen web workers!

Divide And Conquer
Yes, each tab can spawn more than one worker. This comes handy in our case as we can split the list and assign a chunk to each worker thread. The results are sent back and combined on the main thread for display.

There you have it: performant front-end filtering, thanks the web workers.
I will write a post demonstrating this use case. The code will be available on GitHub and I'll link it here. 😉

Happy coding!

Tag cloud