# Web worker

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/Web_worker
> Markdown URL: https://mediated.wiki/source/Web_worker.md
> Source: https://en.wikipedia.org/wiki/Web_worker
> Source revision: 1269985386
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

JavaScript script

Web Workers Status Living Standard Year started 3 April 2009 (2009-04-03) First published 3 April 2009 (2009-04-03) Organization W3C WHATWG Committee WHATWG Editors Ian Hickson Domain Multithreaded programming Multiprocessing Website Retired standard: https://www.w3.org/TR/2021/NOTE-workers-20210128/ Latest standard: https://html.spec.whatwg.org/multipage/workers.html

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

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](/source/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](/source/Document_Object_Model), they can facilitate [concurrent](/source/Concurrency_(computer_science)) execution of JavaScript programs.

## Features

Web workers interact with the main document via [message passing](/source/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](/source/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;
var end_value = 10**7;
search: while (n <= end_value) {
  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.[3] The Worker property will be undefined if the [browser](/source/Web_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](/source/Google_Chrome), [Opera](/source/Opera_(web_browser)), [Edge](/source/Microsoft_Edge), [Internet Explorer](/source/Internet_Explorer) (version 10), [Mozilla](/source/Mozilla) [Firefox](/source/Firefox), and [Safari](/source/Safari_(web_browser)).[4][5][6] Mobile Safari for [iOS](/source/IOS_(Apple)) has supported web workers since iOS 5. The [Android](/source/Android_(operating_system)) 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]

## See also

- [Web service worker](/source/Web_service_worker)

## References

1. ^ [***a***](#cite_ref-WHATWG_1-0) [***b***](#cite_ref-WHATWG_1-1) [***c***](#cite_ref-WHATWG_1-2) [***d***](#cite_ref-WHATWG_1-3) [*Web Workers*](https://html.spec.whatwg.org/multipage/workers.html), [WHATWG](/source/Web_Hypertext_Application_Technology_Working_Group), retrieved 2 January 2023

1. **[^](#cite_ref-2)** ["HTML Living Standard"](https://html.spec.whatwg.org/multipage/workers.html#delegation). *Html.spec.whatwg.org*. 30 January 2017. Retrieved 31 January 2017.

1. **[^](#cite_ref-3)** "HTML5 Up and Running" Mark Pilgrim. O'Reilly/Google Press. August 2010

1. **[^](#cite_ref-into_html5_4-0)** "Introducing HTML5", Lawson, B. and Sharp, R., 2011.

1. **[^](#cite_ref-5)** "HTML5 and CSS3" Brian P. Hogan. The Pragmatic Programmers, LLC 2010.

1. **[^](#cite_ref-6)** ["Can I Use... Web Worker"](https://caniuse.com/#search=web%20worker). *caniuse.com*. Retrieved 30 September 2019.

1. **[^](#cite_ref-7)** ["Spotlight: Benchmarking Android 2.1 with Web Workers - Isogenic Engine"](https://web.archive.org/web/20131019092816/http://www.isogenicengine.com/2010/10/25/spotlight-benchmarking-android-2-1-with-web-workers/). Archived from [the original](http://www.isogenicengine.com/2010/10/25/spotlight-benchmarking-android-2-1-with-web-workers/) on 19 October 2013. Retrieved 10 July 2011.

1. **[^](#cite_ref-8)** ["Can I use... Support tables for HTML5, CSS3, etc"](http://caniuse.com/#search=worker). *caniuse.com*. Retrieved 10 June 2017.

## External links

- [Web Workers – W3C](https://web.archive.org/web/20081231150107/http://dev.w3.org/html5/workers/)

- [Web Workers – WHATWG](https://www.whatwg.org/specs/web-workers/current-work/)

- [Using Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) – Mozilla Developer Network

v t e Web interfaces Server-side Protocols HTTP v2 v3 Encryption WebDAV CGI SCGI FCGI AJP WSRP WebSocket Server APIs C NSAPI C ASAPI C ISAPI COM ASP Jakarta Servlet container CLI OWIN ASP.NET Handler Python WSGI Python ASGI Ruby Rack JavaScript JSGI Perl PSGI Portlet container Apache modules mod_include mod_jk mod_lisp mod_mono mod_parrot mod_perl mod_php mod_proxy mod_python mod_wsgi mod_ruby Phusion Passenger Topics Web service vs. Web resource WOA vs. ROA Open API Webhook Application server comparison Scripting Client-side Browser APIs C NPAPI LiveConnect XPConnect C NPRuntime C PPAPI NaCl ActiveX BHO XBAP Web APIs WHATWG Audio Canvas DOM SSE Video WebSockets Web messaging Web storage Web worker XMLHttpRequest W3C DOM events EME File Geolocation IndexedDB MSE SVG WebAssembly WebAuthn WebGPU WebRTC WebXR Khronos WebCL WebGL Others Gears Web SQL Database (formerly W3C) WebUSB Topics Ajax and Remote scripting vs. DHTML Browser extension Cross-site scripting and CORS Hydration Mashup Persistent data Web IDL Scripting Related topics Frontend and backend Microservices REST GraphQL Push technology Solution stack Web page Static Dynamic Web standards Web API security Web application Rich Single-page Progressive Web framework

v t e World Wide Web Consortium (W3C) Products, standards Recommendations ActivityPub Activity Streams ARIA Canonical XML CDF CSS Animations Flexbox Grid DOM EXI EmotionML Geolocation API GRDDL HTML HTML5 IndexedDB ITS JSON-LD Linked Data Notifications MathML Micropub MTOM OWL PLS RDF Schema RDFa RIF SAWSDL SISR SKOS SMIL SOAP SRGS SRI SSML SVG Animation Filter Effects SCXML SHACL SPARQL Timed text VoiceXML WebAssembly WoT TD Web storage WSDL Webmention WebSub WebVTT WOFF WS-Addressing XHTML +RDFa XML Base Encryption Events Information Set Namespace Schema Signature XForms XInclude XLink XOP XPath 2.0 3.x XPointer XProc XQuery XSL XSL-FO XSLT elements Notes IndieAuth XAdES XBL XHTML+SMIL XUP Working drafts CCXML CURIE EME InkML MSE SMIL Timesheets sXBL WebGPU WebXR XFDL XFrames XMLHttpRequest Guidelines Web Content Accessibility Guidelines Initiative Markup Validation Service Web Accessibility Initiative Web Components Deprecated C-HTML HDML JSSS PGML VML WebPlatform Obsoleted P3P XHTML+MathML+SVG Groups, organizations WHATWG Defunct: World Wide Web Foundation Elected AB Board TAG Working CSS SVG WebAssembly WebAuthn Community, business Web Advertising BG WebAssembly CG Closed Device Description (DDWG) HTML Multimodal Interaction Activity (MMI) Software CERN httpd Libwww Browsers Line Mode (1990–) Arena (1993–98) Agora (1994–97) Argo (1994–97) Amaya (browser/editor, 1996–2012) Conferences International World Wide Web Conference (IW3C) Steering Committee (IW3C2) First conference ("WWW1", 1994)

---
Adapted from the Wikipedia article [Web worker](https://en.wikipedia.org/wiki/Web_worker) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/Web_worker?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
