Web worker

from Wikipedia, the free encyclopedia

Web workers allow JavaScript code to be executed in the background separately from the main thread . Web workers come in three types: Dedicated Workers and Shared Workers and Service Workers.

Dedicated workers

The common web worker is called a dedicated worker.

problem

A dialog box stating that a script has stopped responding and asking if you want to quit.
Warning message about a script that is taking so long that it seems to stop responding

Traditionally, browsers only ran JavaScript scripts in a single thread in the foreground. This leads to problems when complex code is to be processed, as this may run for a very long time and thus in the meantime make interaction of the user with the website difficult or even impossible. Most browsers therefore offer a way to abort a long running script. But even in this case the browser can be blocked for a short time by a script, and the time limit also creates a problem for scripts when they are supposed to process a complex and therefore computationally intensive task. The Web Worker API was developed to address these problems.

Web worker API

A new web worker can be set up via . The browser loads the specified script into a new thread. Communication with the worker can take place in both directions via the method and the event listener . new Worker( 'skript.js' )postMessage onmessage

Within the worker, all JavaScript functions are available that are defined in the ECMAScript standard, as are many of the browser-typical APIs. An important exception to this is the Document Object Model . The worker code has no access to this and must therefore send a message to the main thread to change the page so that it can execute the desired commands.

Variable transfer

postMessageVariables of simple types, numbers, strings, arrays and simple objects (a little more than is possible in JSON ) can be transferred via . In contrast to the transfer to functions, a copy is made, i.e. the data is transferred as a value parameter and not as a reference parameter as is usual . Functions and objects in the sense of object-oriented code , on the other hand, must be suitably serialized and deserialized for transfer.

Binary data can be transferred as ArrayBuffer, but then access to the original is no longer possible. Alternatively, one SharedArrayBuffercan be used that can be processed by multiple threads at the same time. Special atomic operations are available for this.

While DOM elements cannot be passed to another thread, this should be made possible to a certain extent for canvas elements . The main thread can OffscreenCanvaspass control to a background thread via an element, where all the usual functions for drawing can be called.

example

The following example searches for prime numbers . These are calculated in sequence in a worker and passed to the main thread for display.

The HTML document embeds the main script directly. This creates a worker and then reacts to messages that this worker sends.

<!DOCTYPE html>
<html>
 <head>
  <title>Worker-Beispiel</title>
 </head>
 <body>
  <p>Die bis jetzt größte gefundene Primzahl ist: <output id="result"></output></p>
  <script>
   var worker = new Worker( 'worker.js' ); // erzeugt neuen Worker
   worker.onmessage = function ( event ) { // wird aufgerufen, wenn Worker eine Nachricht sendet
     document.getElementById( 'result' ).textContent = event.data; // zeigt die gefundene Primzahl an
   };
  </script>
 </body>
</html>

The code for the script worker.jssearches for prime numbers in an endless loop and always informs the main thread when it has found one:

var i, n = 1;
search: while ( true ) {
  n++;
  for ( i = 2; i <= Math.sqrt( n ); i++ ) {
    if ( n % i === 0 ) {
      continue search;
    }
  }
  // n ist eine Primzahl
  postMessage( n );
}

Shared workers

An ordinary worker always belongs to the page that created him. If a user calls the page multiple times in his browser (or different pages from the same domain that use the same worker), several workers are initialized with the same code. If you use one instead SharedWorker, it will be reused.

Service worker

Another special type of web worker is the service worker. This is used for two tasks: On the one hand, it can act as a proxy , and on the other hand, it can receive notifications sent by the server even if no page of the corresponding domain is currently open.

For the task as a proxy, the fetch-event is available in the worker , which is always triggered when the browser requests data from the monitored domain, regardless of whether this is triggered by AJAX , user navigation or other causes. The worker can intercept the event and make the requested data available in another way if necessary. In particular, service workers are intended as a replacement for application cache for the implementation of web apps that should also work offline. The specification is so flexible, however, that numerous other options beyond a simple cache are possible.

Browser support

All common browsers offer at least basic support for web workers, Mozilla Firefox from version 3.5, Google Chrome from version 4, Internet Explorer from version 10, Edge from version 12. Support has been and will be expanded with newer versions. Service workers are available in Firefox from version 44, in Chrome from version 40 and are not yet fully implemented in these browsers either.

Norms and standards

Web Workers is standardized by the W3C . The current specification is from September 24, 2015.

Web links

Individual evidence

  1. Intensive JavaScript . Mozilla Developer Network . Retrieved June 27, 2016.
  2. ^ Lars T Hansen: A Taste of JavaScript's New Parallel Primitives . Published on May 5, 2016 in Mozilla Hacks, accessed June 27, 2016.
  3. ^ Nick Desaulniers: WebGL Off the Main Thread . Published on January 22, 2016 in Mozilla Hacks, accessed on June 27, 2016.
  4. Example adapted from: Ian Hickson: Web Workers . W3C Draft of September 24, 2015.
  5. ^ Dan Callahan: Web Push Arrives in Firefox 44 . Published January 26, 2016 in Mozilla Hacks, Retrieved June 27, 2016.
  6. ^ Service Workers. Motivation. W3C Draft June 25, 2015.
  7. ^ Salva: Beyond Offline . Published December 21, 2015 in Mozilla Hacks, accessed June 27, 2016.
  8. Can I use: Web Workers . Retrieved June 27, 2016.
  9. Is ServiceWorker ready? Retrieved June 27, 2016.