HTML and CSS Reference
In-Depth Information
The HTML5 Web Workers API
Web Workers is an API that can be used to execute scripts in the background independent from any user interface
scripts. Consequently, the user interface is not affected, and all browser tasks are performed without any delay.
The “worker” in Web Workers refers to a script stored in an external file, which is loaded and executed in the
background (Listing 6-16).
Listing 6-16. Creating a “Worker”
new Worker("worker.js");
While complex JavaScript codes might hang your browser (such as giving an “unresponsive script” warning),
the Web Workers API makes it possible to avoid user interruption, while the browser performs tasks such as event
handling, DOM manipulations, queries, and processes.
Since JavaScript was originally designed to run in a single-threaded environment—that is, multiple scripts
cannot be run simultaneously—Web Workers can be considered as an api that brings threading to JavaScript.
In our example, we create a “worker” that counts up from 0 to 10,000 in the background. First, two push buttons
are needed in the document body to start and stop counting (two input elements with unique identifiers), and a
paragraph is needed with an identifier ( <p id="result"> ) where the result will be displayed (Listing 6-17).
Listing 6-17. Markup of a Web Worker Example
<h1>Start/Stop the Worker</h1>
<input id="start" type="button" value="Start">
<input id="stop" type="button" value="Stop">
<h1>The results</h1>
<p id="result">Click Start to start the Worker</p>
(function () {
function createWorker () {
worker = new Worker("webworker.js");
document.getElementById("start").onclick = function () {
worker.postMessage(0); // initial value
worker.onmessage = function (evt) {
document.getElementById("result").innerHTML =;
worker.onerror = function (evt) {
document.getElementById("result").innerHTML = "Error";
Search WWH ::

Custom Search