HTML 5 Web Workers

Web Workers are initialized with the URL of a JavaScript file, which contains the code the worker will execute. This code sets event listeners and communicates with the script that spawned it. The URL for the JavaScript file can be a relative or absolute URL with the same origin (the same scheme, host, and port) as the main page:

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

Loading and Executing Additional JavaScript

An application composed of several JavaScript files can contain <script> elements that synchronously load JavaScript files as the page loads. However, because Web Workers do not have access to the document object, there is an alternative mechanism for synchronously importing additional JavaScript files from within workers- importScripts:

importScripts("helper.js");

Importing a JavaScript file simply loads and executes JavaScript into an existing worker. Multiple scripts can be imported by the same call to importScripts. They are executed in the order specified:

importScripts("helper.js", "anotherHelper.js");

Communicating with HTML5 Web Workers

Once the Web Worker is spawned, you can use the postMessage API to send data to and from Web Workers. This is the same postMessage API that is used for cross-frame and cross-window communication. postMessage can be used to send most JavaScript objects, but not functions or objects with cyclic references.

Handling Errors

Unhandled errors in an HTML 5 Web Worker script fire error events on the Web Worker object. Listening For these error events is especially important when you are debugging scripts that make use of Web Workers. The following shows an example of an error handling function in a Web Worker JavaScript file that logs errors to the console:

function errorHandler(e)
{
console.log(e.message, e);
}








To handle the errors, you must add an event listener to the main page:


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

Stopping HTML 5 Web Workers

Web Workers don’t stop by themselves; but the page that started them can stop them. You may want to reclaim resources when a Web Worker is no longer needed―perhaps when the main page is notified that the Web Worker has finished its tasks. You may also wish to cancel a long-running task in response to user intervention, as follows. Calling terminate stops the Web Worker. A terminated Web Worker will no longer respond to messages or perform any additional computations. You cannot restart a worker; instead, you can create a new worker using the same URL.

worker.terminate();

Using Timers

Although HTML 5 Web Workers cannot access the window object, they can make use of the full JavaScript
timing API, typically found on the global window:


var t = setTimeout(postMessage, 2000, "delayed message");

No comments:

Post a Comment