Web worker

Last updated
Web Workers
Status Living Standard
Year started3 April 2009 (2009-04-03)
First published3 April 2009 (2009-04-03)
Organization
CommitteeWHATWG
Editors Ian Hickson
Domain
Website

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 scripts that may also have been executed from the same HTML page. [1] Web workers are often able to utilize multi-core CPUs more effectively. [2]

Contents

The W3C and WHATWG envision web workers as long-running scripts that are not interrupted by 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 web worker specification is part of the HTML Living Standard. [1]

Overview

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

Web workers run outside the context of an HTML document's scripts. Consequently, while they do not have access to the DOM, they can facilitate concurrent 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.

varworker=newWorker("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();}functiondoSomething(){//do workworker.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: <outputid="result"></output></p><script>varworker=newWorker('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:

varn=1;varend_value=10**7;search:while(n<=end_value){n++;for(vari=2;i<=Math.sqrt(n);i++)if(n%i==0)continuesearch;// 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. [3] 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

functionbrowserSupportsWebWorkers(){returntypeofwindow.Worker==="function";}

Web workers are currently supported by Chrome, Opera, Edge, Internet Explorer (version 10), Mozilla Firefox, and Safari. [4] [5] [6] 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. [7] [8]

Related Research Articles

<span class="mw-page-title-main">Document Object Model</span> Convention for representing and interacting with objects in HTML, XHTML, and XML documents

The Document Object Model (DOM) is a cross-platform and language-independent interface that treats an HTML or XML document as a tree structure wherein each node is an object representing a part of the document. The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree; with them one can change the structure, style or content of a document. Nodes can have event handlers attached to them. Once an event is triggered, the event handlers get executed.

An HTML element is a type of HTML document component, one of several types of HTML nodes. The first used version of HTML was written by Tim Berners-Lee in 1993 and there have since been many versions of HTML. The current de facto standard is governed by the industry group WHATWG and is known as the HTML Living Standard.

Web standards are the formal, non-proprietary standards and other technical specifications that define and describe aspects of the World Wide Web. In recent years, the term has been more frequently associated with the trend of endorsing a set of standardized best practices for building web sites, and a philosophy of web design and development that includes those methods.

DOM Events are a signal that something has occurred, or is occurring, and can be triggered by user interactions or by the browser. Client-side scripting languages like JavaScript, JScript, VBScript, and Java can register various event handlers or listeners on the element nodes inside a DOM tree, such as in HTML, XHTML, XUL, and SVG documents.

A user interface markup language is a markup language that renders and describes graphical user interfaces and controls. Many of these markup languages are dialects of XML and are dependent upon a pre-existing scripting language engine, usually a JavaScript engine, for rendering of controls and extra scriptability.

Push technology, also known as server push, refers to a communication method, where the communication is initiated by a server rather than a client. This approach is different from the "pull" method where the communication is initiated by a client.

The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images. It is a low level, procedural model that updates a bitmap. HTML5 Canvas also helps in making 2D games.

<span class="mw-page-title-main">HTML5</span> Fifth and previous version of hypertext markup language

HTML5 is a markup language used for structuring and presenting hypertext documents on the World Wide Web. It was the fifth and final major HTML version that is now a retired World Wide Web Consortium (W3C) recommendation. The current specification is known as the HTML Living Standard. It is maintained by the Web Hypertext Application Technology Working Group (WHATWG), a consortium of the major browser vendors.

The Web Hypertext Application Technology Working Group (WHATWG) is a community of people interested in evolving HTML and related technologies. The WHATWG was founded by individuals from Apple Inc., the Mozilla Foundation and Opera Software, leading Web browser vendors in 2004.

Extensible HyperText Markup Language (XHTML) is part of the family of XML markup languages which mirrors or extends versions of the widely used HyperText Markup Language (HTML), the language in which Web pages are formulated.

Web storage, sometimes known as DOM storage, is a standard JavaScript API provided by web browsers. It enables websites to store persistent data on users' devices similar to cookies, but with much larger capacity and no information sent in HTTP headers. There are two main web storage types: local storage and session storage, behaving similarly to persistent cookies and session cookies respectively. Web Storage is standardized by the World Wide Web Consortium (W3C) and WHATWG, and is supported by all major browsers.

The HTML5 specification introduced the video element for the purpose of playing videos, partially replacing the object element. HTML5 video is intended by its creators to become the new standard way to show video on the web, instead of the previous de facto standard of using the proprietary Adobe Flash plugin, though early adoption was hampered by lack of agreement as to which video coding formats and audio coding formats should be supported in web browsers. As of 2020, HTML5 video is the only widely supported video playback technology in modern browsers, with the Flash plugin being phased out.

Server-Sent Events (SSE) is a server push technology enabling a client to receive automatic updates from a server via an HTTP connection, and describes how servers can initiate data transmission towards clients once an initial client connection has been established. They are commonly used to send message updates or continuous data streams to a browser client and designed to enhance native, cross-browser streaming through a JavaScript API called EventSource, through which a client requests a particular URL in order to receive an event stream. The EventSource API is standardized as part of HTML5 by the WHATWG. The media type for SSE is text/event-stream.

Modern HTML5 has feature-parity with the now-obsolete Adobe Flash. Both include features for playing audio and video within web pages. Flash was specifically built to integrate vector graphics and light games in a web page, features that HTML5 also supports.

Web Messaging, or cross-document messaging, is an API introduced in the WHATWG HTML5 draft specification, allowing documents to communicate with one another across different origins, or source domains while rendered in a web browser. Prior to HTML5, web browsers disallowed cross-site scripting, to protect against security attacks. This practice barred communication between non-hostile pages as well, making document interaction of any kind difficult. Cross-document messaging allows scripts to interact across these boundaries, while providing a rudimentary level of security.

Content Security Policy (CSP) is a computer security standard introduced to prevent cross-site scripting (XSS), clickjacking and other code injection attacks resulting from execution of malicious content in the trusted web page context. It is a Candidate Recommendation of the W3C working group on Web Application Security, widely supported by modern web browsers. CSP provides a standard method for website owners to declare approved origins of content that browsers should be allowed to load on that website—covered types are JavaScript, CSS, HTML frames, web workers, fonts, images, embeddable objects such as Java applets, ActiveX, audio and video files, and other HTML5 features.

In software development, a polyfill is code that implements a feature of the development environment that does not natively support the feature. Most often, it refers to JavaScript code that implements an HTML5 or CSS web standard, either an established standard on older browsers, or a proposed standard on existing browsers. Polyfills are also used in PHP and Python.

HTML5 Audio is a subject of the HTML5 specification, incorporating audio input, playback, and synthesis, as well as in the browser. iOS

<span class="mw-page-title-main">Paul Irish</span> American web developer

Paul Irish is an American front-end engineer and a developer advocate for the Google Chrome web browser. He is an evangelist in web technologies, including JavaScript and CSS. In 2011, he was named Developer of the Year by The Net Awards for his contributions to the web development landscape and his participation in many popular open source projects.

<span class="mw-page-title-main">Progressive web app</span> Specific form of single page web application

A progressive web application (PWA), or progressive web app, is a type of application software delivered through the web, built using common web technologies including HTML, CSS, JavaScript, and WebAssembly. It is intended to work on any platform with a standards-compliant browser, including desktop and mobile devices.

References

  1. 1 2 3 4 Web Workers, WHATWG , retrieved 2 January 2023
  2. "HTML Living Standard". Html.spec.whatwg.org. 30 January 2017. Retrieved 31 January 2017.
  3. "HTML5 Up and Running" Mark Pilgrim. O'Reilly/Google Press. August 2010
  4. "Introducing HTML5", Lawson, B. and Sharp, R., 2011.
  5. "HTML5 and CSS3" Brian P. Hogan. The Pragmatic Programmers, LLC 2010.
  6. "Can I Use... Web Worker". caniuse.com. Retrieved 30 September 2019.
  7. "Spotlight: Benchmarking Android 2.1 with Web Workers - Isogenic Engine". Archived from the original on 19 October 2013. Retrieved 10 July 2011.
  8. "Can I use... Support tables for HTML5, CSS3, etc". caniuse.com. Retrieved 10 June 2017.