Chapter 9. Web Workers

When your web application requires heavy lifting or background processing on the JavaScript side, the Web Workers API is your answer.

The Web Workers interface spawns real OS-level threads, allowing for data to be passed back and forth between any given threads (or worker). Furthermore, because communication points between threads are carefully controlled, concurrency problems are rare. You cannot access components unsafe to threads or the DOM, and you have to pass specific data in and out of a thread through serialized objects. So you have to work extremely hard to cause problems in your code. Regardless of how you plan to use Web Workers in your application, the main idea behind processing any behind-the-scenes data lies in the idea of creating multiple workers (or threads) in the browser.

As of this writing, Safari, Safari for iOS5, Chrome, Opera, and Mozilla Firefox support the Web Workers API, but Internet Explorer does not. (Internet Explorer 10 did add support for Web Workers in Platform Preview 2.) Web Workers in Android versions 2.0 and 2.1 support Web Workers, as well, but later versions of Android do not. The only shim currently available for Web Workers makes use of Google Gears. If the core Web Workers API is not supported on a device or browser, you can detect if Google Gears is installed. For more details, see http://html5-shims.googlecode.com/svn/trunk/demo/workers.html.

With Web Workers and its multithreaded approach, you do not have access ...

Get HTML5 and JavaScript Web Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.