Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
143023864X_HT5.pdf
Скачиваний:
8
Добавлен:
21.02.2016
Размер:
7.98 Mб
Скачать

C H A P T E R 10

Using the Web Workers API

JavaScript is single-threaded. As a result, long-lasting computations (not necessarily due to poorly written code) will block the UI thread and make it impossible to add text to text boxes, click buttons, use CSS effects, and, in most browsers, open new tabs until control has returned. As an answer to that problem, HTML5 Web Workers provide background-processing capabilities to web applications and typically run on separate threads so that JavaScript applications using Web Workers can take advantage of multicore CPUs. Separating long-running tasks into Web Workers also avoids the dreaded slow-script warnings, shown in Figure 10-1, that display when JavaScript loops continue for several seconds.

Figure 10-1. Slow script warning in Firefox

As powerful as Web Workers are, there are also certain things they cannot do. For example, when a script is executing inside a Web Worker it cannot access the web page’s window object (window.document), which means that Web Workers don’t have direct access to the web page and the DOM API. Although Web Workers cannot block the browser UI, they can still consume CPU cycles and make the system less responsive.

Let’s say you want to create a web application that has to perform some background number crunching, but you do not want those tasks to interfere with the interactivity of the web page itself. Using Web Workers, you can spawn a Web Worker to perform the tasks and add an event listener to listen to messages from the Web Worker as they are sent.

Another use case for Web Workers could be an application that listens for broadcast news messages from a back-end server, posting messages to the main web page as they are received from the back-end server. This Web Worker might use Web Sockets or Server-Sent Events to talk to the back-end server.

In this chapter, we’ll explore what you can do with Web Workers. First, we’ll discuss how Web Workers work and the level of browser support available at the time of this writing. Then, we’ll discuss how you can use the APIs to create new workers and how to communicate between a worker and the context that spawned it. Finally, we’ll show you how you can build an application with Web Workers.

241