What is "web-worker"

A web worker, as defined by the World Wide Web Consortium (W3C) and Web Hypertext Application Technology Working Group (WHATWG), is a Javascript script that runs at the bottom of an HTML page, independent of other user interface (UI) related scripts that may have been executed from the same HTML page.

Example of web worker:

The simplest use of a web worker is to perform a time-consuming computational task without interrupting the user interface (UI).

In this example, the main document initializes a web worker to calculate prime numbers, and progressively displays the most recently found prime number.

The main page is as follows:

<!DOCTYPE html>
<html>
 <head>
  <title>Worker example: One-core computation</title>
 </head>
 <body>
  <p>The highest prime number discovered so far is: <output id="result"></output></p>
  <script>
   var worker = new Worker('worker.js');
   worker.onmessage = function (event) {
     document.getElementById('result').textContent = event.data;
   };
  </script>
 </body>
</html>

The call to the builder Worker() creates a web worker and returns an object worker representing that web worker, which is used to communicate with the web worker. The event onmessage that object allows the code to receive messages from the web worker.

The Web Worker code is as follows:

var n = 1;
search: while (true) {
  n += 1;
  for (var i = 2; i <= Math.sqrt(n); i += 1)
    if (n % i == 0)
      continue search;
  // found a prime!
  postMessage(n);
}

To send a message back to page, it uses method postMessage() when a prime number is found.

References: