Web Workers
Encyclopedia
Web Workers define an API
Application programming interface
An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...

 for running scripts
Scripting language
A scripting language, script language, or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the...

, basically JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

, in the background independently of any user interface
User interface
The user interface, in the industrial design field of human–machine interaction, is the space where interaction between humans and machines occurs. The goal of interaction between a human and a machine at the user interface is effective operation and control of the machine, and feedback from the...

 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
Web browser
A web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier and may be a web page, image, video, or other piece of content...

 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.

Overview

Web Workers allow for concurrent
Concurrency (computer science)
In computer science, concurrency is a property of systems in which several computations are executing simultaneously, and potentially interacting with each other...

 execution of the browser threads
Thread (computer science)
In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process...

 and one or more JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 threads running in the background. The browser which follows a single thread of execution will have to wait on JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 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 is a separate specification from HTML5 specification but can be used with HTML5.

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

When Web Workers run in the background, they do not have direct access to the DOM
Document Object Model
The Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...

 but communicate with the document by message passing
Message passing
Message passing in computer science is a form of communication used in parallel computing, object-oriented programming, and interprocess communication. In this model, processes or objects can send and receive messages to other processes...

. It allows for a multi-threaded
Thread (computer science)
In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process...

 execution of JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 programs.

Features

Web Workers interact with the document via message passing
Message passing
Message passing in computer science is a form of communication used in parallel computing, object-oriented programming, and interprocess communication. In this model, processes or objects can send and receive messages to other processes...

. The following code loads a JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 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
worker.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:




Worker example: One-core computation


The highest prime number discovered so far is:







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. 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. The window property will be undefined if the browser
Web browser
A web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier and may be a web page, image, video, or other piece of content...

 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
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 such as Modernizr
Modernizr
Modernizr is a small JavaScript library that detects the availability of native implementations for next-generation Web Technologies. These technologies are new features that stem from the ongoing HTML5 and CSS 3 specifications.-Overview:...

 can also be used to detect browser functionality for Web Workers. Web Workers are currently supported by Safari
Safari (web browser)
Safari is a web browser developed by Apple Inc. and included with the Mac OS X and iOS operating systems. First released as a public beta on January 7, 2003 on the company's Mac OS X operating system, it became Apple's default browser beginning with Mac OS X v10.3 "Panther". Safari is also the...

, Chrome
Google Chrome
Google Chrome is a web browser developed by Google that uses the WebKit layout engine. It was first released as a beta version for Microsoft Windows on September 2, 2008, and the public stable release was on December 11, 2008. The name is derived from the graphical user interface frame, or...

, Opera
Opera
Opera is an art form in which singers and musicians perform a dramatic work combining text and musical score, usually in a theatrical setting. Opera incorporates many of the elements of spoken theatre, such as acting, scenery, and costumes and sometimes includes dance...

 and Mozilla
Mozilla
Mozilla is a term used in a number of ways in relation to the Mozilla.org project and the Mozilla Foundation, their defunct commercial predecessor Netscape Communications Corporation, and their related application software....

 Firefox. Web workers are not yet supported by Internet Explorer
Internet Explorer
Windows Internet Explorer is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems, starting in 1995. It was first released as part of the add-on package Plus! for Windows 95 that year...

. Internet Explorer 10
Internet Explorer 10
Windows Internet Explorer 10 is the next version of Internet Explorer currently being developed by Microsoft, and the successor to Internet Explorer 9. On April 12, 2011, Microsoft released the first "IE10 Platform Preview", which only runs on Windows 7; later platform previews only run on Windows 8...

 added support for Web Workers in Platform Preview 2. Web workers are supported in Safari for iOS 5, and in Android (operating system) 2.0 and later.
External links
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK