Jump to content

Web worker

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 131.107.0.91 (talk) at 21:34, 25 May 2011 (Trivial wording change to make it easier to distinguish supported vs. unsupported browsers.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Web Workers define an API for running scripts, basically JavaScript, 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 as they could hog system resources. Browser implementation of Web Workers are different.

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

Overview

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 in the background. Web Worker specification [1] is a separate specification from HTML5 specification [2][3] but can be used with HTML5.

There are two types of web workers [1]: Dedicated worker and Shared worker

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

Features

Web Workers interact with the document via message passing. The following code loads a JavaScript file

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

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

	worker.postMessage("Hello World!");


The method onmessage is used to retrieve information from the worker

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

	worker.close

Once a worker is terminated, it goes out of scope and 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 type="text/javascript">
   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 += 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 the page, the postMessage() method is used to post a message when a prime is found.[1] The technique employed in the example is similar to Python's yield.

Support

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

The following example code checks for Web Worker support on a browser

	function detect_web_worker() {
		return !!window.Worker;
	}

Third party libraries for JavaScript such as Modernizr[5] can also be used to detect browser functionality for Web Workers. Web Workers is currently supported by Safari, Chrome, Opera and Mozilla Firefox [3][6]. Web workers are not yet supported by Internet Explorer, iOS 4.2, and Android.

See also

References

  1. ^ a b c d Web Workers, WHATWG {{citation}}: Unknown parameter |access date= ignored (|access-date= suggested) (help)
  2. ^ http://dev.w3.org/html5/spec/overview.html
  3. ^ a b "Introducing HTML5", Lawson, B. and Sharp, R., 2011.
  4. ^ "HTML5 Up and Running" Mark Pilgrim. O'Reilly/Google Press. August 2010
  5. ^ http://www.modernizr.com/ accessed 2011/03/30
  6. ^ "HTML5 and CSS3" Brian P. Hogan. The Pragmatic Programmers, LLC 2010.