Layout Options

  • Fixed Header
    Makes the header top fixed, always visible!
  • Fixed Sidebar
    Makes the sidebar left fixed, always visible!
Html 5 Webworks
Navigation menus are one of the basic building blocks for any web or mobile app.

Description

The Web Workers API enables background processing capabilities to web applications.

Note: When a script is running inside a Web Worker it cannot access the web page's window object (window.document). In other words, Web Workers do not have direct access to the web page / DOM API.

HTML5 and HTML4.01 Differences

This API is new for HTML5.

Creating a Web Worker

To create a web worker, use code similar to the following:

worker = new Worker("worker.js");

Parameters

Parameter Description
worker.js (required) Specifies the URL of a JavaScript file, which contains the code the worker will execute

Communicating with Web Workers

To send data to and from a web worker, use the postMessage API.

To send a message TO a worker, use the following form:

worker.postMessage("message to worker");

To receive messages FROM a worker, set up a listener similar to the following:

worker.addEventListener("message", messageHandler, true);

function messageHandler(e) {
  // process message from worker
}

Note: Use similar code to listen for and receive messages WITHIN the Web Worker.

Handling Errors

Unhandled errors in a web worker script raise events on the Web Worker itself. It is important to listen to these events which can be done by adding a listener similar to the following:

function errorHandler(e) {
  // handle errors here
  console.log(e.message, e);
}

worker.addEventListener("error", errorHandler, true);

Terminating Web Workers

To stop a web worker, use the terminate() function:

worker.terminate();

Note: The terminate() function must be called from OUTSIDE the Web Worker.

Examples

The following example shows how to check for support of this API:

if (typeof(Worker) !== "undefined")) {
  // Web Workers supported
}
else {
  // Web Workers not supported
}

Browser Support

Chrome Firefox IE Safari Opera

Miscellaneous Information

Defined In: HTML5