Web Worker(s); — Outsource your JavaScript

March 12, 2018 0 Comments

Web Worker(s); — Outsource your JavaScript



alert(“Photo by Igor Ovsyannykov on Unsplash”);

I bet that you heard at least a million times, how JavaScript is single thread programming language. Which actually just means that it has single execution stack (check this awesome talk by Philip Roberts, for more insight on what is event loop).

Having 1 execution stack means, that no matter of the async nature of the web APIs such is setTimeout or XMLHttpRequest, they are eventually going to get into the same execution queue.

Async doesn’t mean multi thread, just non blocking.

To conclude, Why web workers?

Simply because Web Workers are yet another WEB API. Just that this API comes with the real support for multi-threading. You can even think that instantiating the Web Worker is like opening the new browser tab in the background (without the DOM and some other stuff, but we will get back to that soon).

There is no native support for web workers in NodeJS. The fact that it is called web worker says it all. Web workers are in fact not part of the JavaScript. Since NodeJS does not run in a browser, it does not implement the WEB APIs.

Main reason for not implementing the concept of Workers in node is the fact that node was initially built to be executed in a single thread and any introduction of multi threading would mean serious redesign of the core system. Which is not trivial.

This is maybe too obvious. But even if you postpone execution of some calculations that does not solve the problem, just delays the inevitable.

Eg. doing JSON.parse() immediately after the async action, can instantly block the execution stack. Not to mention any other further data processing.
Such computations should ideally be done on the Back-End, or at least within the Worker.

Let’s say that we fetch something from the API and receive the huge data-set. Once the async action of fetching is done we need to reformat the data-set, then() modify some things and reorder it. Common scenario (sadly, or in simple words, probably lazy BE). Immediately after we start doing this reformatting / reordering, sync action occurs and our JavaScript single execution stack gets blocked.

Web Workers should be a taboo topic if you need to directly modify…
Window object
Parent object

It’s always better to know limitations of the tool, before you start using it.

Web workers are able to access…
Navigator object { …offline, online, userAgent }
Location object { …host, href }
XMLHttpRequest (not available in ServiceWorker, use fetch API instead)

Worker resides in the global scope 
(Window obj) and it can be instantiated with new Worker();
Many Workers per tab.
Is VERY well supported!

ServiceWorker needs to be registered via navigator.serviceWorker.register();
One serviceWorker per origin (domain).
No XMLHttpRequest, only fetch!
It can be used as a proxy with full caching support. PWA depend on it heavily for providing the “offline” experience to the end user.
It have very limited support.

main context become friend with the Worker… 
const worker = new Worker('webworker.js');
main context sends some data to the Worker… 
worker.postMessage({ ...data });
 webworker is listening inside of webworker.js
it receives the data / process it and returns it back

onmessage = event => {
return process(event.data);
main context waits for the response… 
worker.onmessage = event => {

When you start working with web workers you first realize the importance of communication between worker and the main context of execution.

Consuming Web Workers is simple as, passing some data to the worker > processing that data within the worker > returning the data from worker to the main execution context (your app).

… and that is it!

Where can I learn more about the actual syntax?

Is it safe?

If you need assistance with the topic feel free to contact me on Twitter or place a comment below.

Tag cloud