Web Workers appeared about eight years ago but we still don't mention it much in the front-end scence.
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.
One word: Performance.
- 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.
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.
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.