HTML - Web Worker

About

A worker is a script that run in the background independently of any user interface scripts.

They can run in parallel to their main page. This allows for thread-like operation with message-passing as the coordination mechanism.

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.

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

Example

The 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);
}

where:

Worker example: One-core computation

 <p>The highest prime number discovered so far is: <output id="result"></output></p>
  • The Worker() constructor call creates a worker and returns a Worker object representing that worker, which is used to communicate with the worker.
var worker = new Worker('https://datacadamia.com/doku.php?do=export_code&id=web:html:worker&codeblock=0');
  • That object's onmessage event handler allows the code to receive messages from the worker.
worker.onmessage = function (event) {
     document.getElementById('result').textContent = event.data;
};

More example (With IO, …): Web Workers examples

Documentation / Reference





Discover More
Browser
Browser - Worker (Javascript)

Web Workers makes it possible to run a script operation in a background thread separate from the main execution thread of a web application. They are part of the web api (ie browser api) Same as workers...
HTML - (Cross-document|Web) Messaging

Two mechanisms for communicating between browsing contexts in HTML documents. A messaging system that allows documents to communicate with each other regardless of their source domain, in a way designed...
How to load a script dynamically with Javascript?

This page shows you how you can load a script dynamically with Javascript to load and use it when needed. In short, if you add: a script via an DOM element, it will be executed (via append or insertAdjacentElement)...
How to preload HTML resource (Javascript, StyleSheet)

This article shows you how to preload HTML resources to use them at a later time.
What is the script HTML element?

A client-side script is a program that is: linked (server-side script) or directly embedded in an HTML document (in-line script) Scripts in HTML have “run-to-completion” semantics, meaning that...



Share this page:
Follow us:
Task Runner