O'Reilly logo

HTML5 Hacks by Jeff Burtoft, Jesse Cravens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 8. WebWorker API

The WebWorker API provides a simple set of methods for web content to run scripts in background threads. Web workers are executed from a main browser window but run independently and in parallel. Once a script in the main thread spawns a worker, the worker can send messages back by posting them to a defined event handler. Data is serialized, not cloned, as it is passed back and forth. This is important to note because poor design or use of too many workers can actually cause performance issues.

Web workers are beneficial in that they run without impacting the other user interface scripts executed from the main window, but they do have limitations. They have limited access to core JavaScript, and no access to the Document Object Model (DOM).

However, you can perform I/O through the XMLHttpRequest object and even import third-party scripts, as you will see in [Hack #68].

There are three types of web workers: inline, dedicated, and shared. Browser adoption for shared workers is still very sparse, so most of the following hacks will focus on the simpler, dedicated worker.

In the last hack in this chapter, [Hack #69], you will see how shared web workers allow any number of browser window contexts to communicate with a single worker simultaneously.

Why are web workers so important to web application developers today? It has to do with how browsers handle JavaScript.

How Browsers Handle JavaScript

JavaScript runs in the same thread as the rest of the browser UI, and as ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required