Web Workers in JavaScript
Most of web development is low intensity from a processing perspective and usually intensive work can be shifted to a server. Though there are cases such as complex animations and interactivity where that is not possible. Since JavaScript runs in the browser on the same thread that the rest of the User Interface runs, intensive code can end up making the user experience very poor.
This is where Web Workers come in. They allow JS code to execute in a seperate thread that does not interfere with the GUI thread. Provided that: 1. They do not access the window object; they have their own scope 2. They do no DOM manipulations
Here is a simple example of complex visual processing link. HTML:
<p>Some Content Before</p> <b>Fib(40): </b> <span id="result1">Calculating...</span><br/> <b>Fib(10): </b> <span id="result2">Calculating...</span>
JS:
var fib = function(n) { if (n < 2) { return n; } return fib(n - 1) + fib(n - 2); }; document.querySelector('#result1').innerHTML = fib(42); document.querySelector('#result2').innerHTML = fib(40);
Try typing or interacting with the page in another way and you will notice you cannot. That is because the UI is locked up while processing which is a disaster for user experience. Here is what it looks like with threads link:
var WorkerScript = (function() { var onmessage = function(e) { var fib = function(n) { if (n < 2) { return n; } return fib(n - 1) + fib(n - 2); }; postMessage(fib(e.data)); }; }).toString(); var blob = new Blob([ WorkerScript.slice(WorkerScript.indexOf('{') + 1, WorkerScript.lastIndexOf('}')) ]); var worker1 = new Worker(window.URL.createObjectURL(blob)); var worker2 = new Worker(window.URL.createObjectURL(blob)); worker1.onmessage = function(e) { document.querySelector('#result1').innerHTML = e.data; worker1.terminate(); }; worker2.onmessage = function(e) { document.querySelector('#result2').innerHTML = e.data; worker2.terminate(); }; worker1.postMessage(42); worker2.postMessage(40);
Notice how the UI can now be interacted with. Usually a Web Worker would be loaded with an external script:
var worker = new Worker("webWorkerScript.js");
But it is simpler to use the Blob API for an example. Thanks to this post for the idea.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/webWorker.js














