Introduction to WEB Workers

WEB Workers is a new HTML5 feature, which allows to run JS in the background.

Main thread, which is often responsible for handling UI, can be occupied by the UI rendering, so it can be a good idea to move the execution of scripts to the background thread.

WEB Workers solve exactly that. By using them, we can execute long running scripts to save some execution time.

How to start a dedicated WEB Worker

var myWorker = new Worker('someWorkerScript.js');

Because the Worker object is a property of window object, for the sake of backward compatibility, we can check if it exists:

if (window.Worker) {
  // @todo: do stuff
}

How to communicate with the main thread

There are 2 methods, which you can use to communicate messages back and forth from main thread to WEB Worker: postMessage()

A simple use case

Let's see how WEB Workers can be used in a real life scenario. 

You can have a website, where like in this website, you'd have many posts and many code snippets and you would want to highlight them in many different coding languages. For this you can use highlight.js npm library. 

While you can simply call the necessary function like this: hljs.initHighlightingOnLoad();. if your page contains multiple and/or big code snippets, you may find that it takes a considerable time before every code snippets become highlighted and it also may temporarily freeze your browser.

This is how the code would look without using WEB Worker:

require('highlight.js/styles/mono-blue.css');

import hljs from 'highlight.js';

hljs.initHighlightingOnLoad();

Same code using WEB Worker

main file: app.js

require('highlight.js/styles/mono-blue.css');

import hljs from 'highlight.js';

if (window.Worker) {
    addEventListener('load', () => {
        const code = document.querySelector('#code');
        const worker = new Worker('worker.js');
        worker.onmessage = (event) => { code.innerHTML = event.data; }
        worker.postMessage(code.textContent);
    });
} else {
    hljs.initHighlightingOnLoad();
}

worker file: worker.js

onmessage = (event) => {
    importScripts('<path>/highlight.pack.js');
    const result = self.hljs.highlightAuto(event.data);
    postMessage(result.value);
};

to be continued...