Web worker

A web worker, as defined by the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG), is a JavaScript script executed from an HTML page that runs in the background, independently of other user-interface scripts that may also have been executed from the same HTML page.[1] Web workers are able to utilize multi-core CPUs more effectively.

The W3C and WHATWG envision web workers as long-running scripts that are not interrupted by user-interface scripts (scripts that respond to clicks or other user interactions). Keeping such workers from being interrupted by user activities should allow Web pages to remain responsive at the same time as they are running long tasks in the background.

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

The W3C and the WHATWG are currently in the process of developing a definition for an API for web workers.[1]

Overview

As envisioned by WHATWG, web workers are relatively heavy-weight. They are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost.[1]

Web workers are not intended or expected to be used in large numbers as they could hog system resources.

Web Workers allow for concurrent execution of the browser threads and one or more JavaScript threads running in the background. The browser which follows a single thread of execution will have to wait on JavaScript programs to finish executing before proceeding and this may take significant time which the programmer may like to hide from the user. It allows for the browser to continue with normal operation while running the script in the background. The web worker specification[1] is a separate specification from the HTML5 specification[2][3] and can be used with HTML5.

There are two types of web workers:[1] dedicated and shared workers.

When web workers run in the background, they do not have direct access to the DOM but communicate with the document by message passing. This allows for multi-threaded execution of JavaScript programs.

Features

Web workers interact with the main document via message passing. The following code creates a Worker that will execute the JavaScript in the given file.

var worker = new Worker("worker_script.js");

To send a message to the worker, the postMessage method of the worker object is used as shown below.

worker.postMessage("Hello World!");

The onmessage property uses an event handler to retrieve information from a worker.

worker.onmessage = function(event) {
	alert("Received message " + event.data);
	doSomething();
}
	
function doSomething() {
	//do work
	worker.postMessage("Work done!");
}

worker.terminate();

Once a worker is terminated, it goes out of scope and the variable referencing it becomes undefined; at this point a new worker has to be created if needed.

Example

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:

<!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 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++;
  for (var i = 2; i <= Math.sqrt(n); i++)
    if (n % i == 0)
      continue search;
  // found a prime!
  postMessage(n);
}

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

Support

If the browser supports web workers, a Worker property will be available on the global window object.[4] The Worker property will be undefined if the browser does not support it.

The following example code checks for web worker support on a browser

function browserSupportsWebWorkers() {
  return typeof window.Worker === "function";
}

Web workers are currently supported by Chrome, Opera, Internet Explorer (version 10), Mozilla Firefox, and Safari.[3][5] Mobile Safari for iOS has supported web workers since iOS 5. The Android browser first supported web workers in Android 2.1, but support was removed in Android versions 2.2–4.3 before being restored in Android 4.4.[6][7]

See also

References

  1. 1 2 3 4 5 6 Web Workers, WHATWG, retrieved 2010-06-03
  2. http://dev.w3.org/html5/spec/overview.html
  3. 1 2 "Introducing HTML5", Lawson, B. and Sharp, R., 2011.
  4. "HTML5 Up and Running" Mark Pilgrim. O'Reilly/Google Press. August 2010
  5. "HTML5 and CSS3" Brian P. Hogan. The Pragmatic Programmers, LLC 2010.
  6. http://www.isogenicengine.com/2010/10/25/spotlight-benchmarking-android-2-1-with-web-workers/
  7. http://caniuse.com/#search=worker

External links

Specifications
Browser
This article is issued from Wikipedia - version of the 12/4/2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.