25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 8 ■ USING THE <strong>HTML</strong>5 WEB WORKERS API<br />

In this example, you test for browser support in the loadDemo function, which might be called when<br />

the page is loaded. A call to typeof(Worker) will return the window’s global Worker property, which will<br />

be undefined if the browser doesn’t support the Web Workers API. In this example, the page is updated<br />

to reflect whether there is browser support by updating a previously defined support element on the<br />

page with a suitable message, as shown at the top of Figure 8-2.<br />

Figure 8-2. Example of showing whether <strong>HTML</strong>5 Web Workers is supported<br />

Creating <strong>HTML</strong>5 Web Workers<br />

Web Workers are initialized with the URL of a JavaScript file, which contains the code the worker will<br />

execute. This code sets event listeners and communicates with the script that spawned it. The URL for<br />

the JavaScript file can be a relative or absolute URL with the same origin (the same scheme, host, and<br />

port) as the main page:<br />

worker = new Worker("echoWorker.js");<br />

Loading and Executing Additional JavaScript<br />

An application composed of several JavaScript files can contain elements that synchronously<br />

load JavaScript files as the page loads. However, because Web Workers do not have access to the<br />

document object, there is an alternative mechanism for synchronously importing additional JavaScript<br />

files from within workers—importScripts:<br />

importScripts("helper.js");<br />

Importing a JavaScript file simply loads and executes JavaScript into an existing worker. Multiple<br />

scripts can be imported by the same call to importScripts. They are executed in the order specified:<br />

importScripts("helper.js", "anotherHelper.js");<br />

Communicating with <strong>HTML</strong>5 Web Workers<br />

Once the Web Worker is spawned, you can use the postMessage API to send data to and from Web<br />

Workers. This is the same postMessage API that is used for cross-frame and cross-window<br />

communication. postMessage can be used to send most JavaScript objects, but not functions or objects<br />

with cyclic references.<br />

195

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!