Web worker

From Seo Wiki - Search Engine Optimization and Programming Languages

Jump to: navigation, search

Web worker defines an API for running scripts in the background independently of any user interface scripts.

This allows for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.

Web workers are relatively heavy-weight, and are not intended to be used in large numbers. For example, it would be inappropriate to launch one web worker for each pixel of a four megapixel image.

Generally, web workers are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost.[1]


The simplest use of web workers is for performing a computationally expensive task without interrupting the user interface.

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

The main page is as follows:

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

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

The web worker itself 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!

To send a message back to the page, the postMessage() method is used to post a message when a prime is found.[1]


  1. 1.0 1.1 "Web Workers". WHATWG. http://www.whatwg.org/specs/web-workers/current-work/. Retrieved 30 October 2009. 
Personal tools

Served in 0.122 secs.