HTML and CSS Reference
In-Depth Information
Web Workers
Earlier in this topic we discussed how JavaScript utilizes a single thread to perform all pro-
cessing, and that this is the same thread the browser uses to render the web page. Although
there are rudimentary ways of controlling when a piece of code executes using setTimeout ,
there is no way to execute JavaScript on a seperate thread, or in multiple threads concur-
Most modern computers, and even most smart phones, are capable of executing multiple
threads concurrently since most devices now contain multiple processors or multiple cores.
In addition, most software engineers expect multithreading libraries to be built into modern
There are very good reasons why JavaScript is limited to a single thread, for instance, to pre-
vent multiple threads attempted to update the same portion of the Document Object Model
simultaneously. There is however a lot of other computation where there would be no issue
with multiple threads executing simultaneously.
As an example, consider the CSV file that was processed in the previous chapter. The pro-
cess of converting a JavaScript string into a set of objects is a self-contained operation, and
has no bearing on the DOM (at least until we refreshed the table at the end of the process-
ing). It should therefore be theoretically possible to execute this processing on a separate
thread, and only revert back to the main browser thread when we need to update the HTML
HTML5 contains an API called Web Workers that allow some degree of multi-threading in
HTML applications. This chapter will introduce the Web Worker API, and examine some
use-cases where it may be appropriate.
A Web Worker is a block of code in its own JavaScript file. The Web Worker typically listens
for messages to be posted to it from the main browser thread. When it receives messages,
it performs whatever computation is required of it, but the big difference is that browsers
will execute this computation on a separate thread, and therefore if the underlying hardware
supports it, this processing can happen concurrently with processing on the main browser
When the Web Worker has finished its processing it can post a message back to the main
browser thread, which will perform whatever it needs to with this result, such as updating
the DOM.
Before looking at what Web Workers can do, we will first look at their restrictions. Web
Workers do not have access to any of the following objects:
Search WWH ::

Custom Search