25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

document.getElementById("helloButton").onclick = function() {<br />

worker.postMessage("Here's a message for you");<br />

}<br />

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

In the preceding example, a message is sent to the Web Worker when the user clicks the Post a<br />

Message button. Next, add an event listener to the page that listens for messages from the Web Worker:<br />

worker.addEventListener("message", messageHandler, true);<br />

function messageHandler(e) {<br />

// process message from worker<br />

}<br />

Coding the <strong>HTML</strong>5 Web Worker JavaScript File<br />

You must now add similar code to theWeb Worker JavaScript file—event handlers must be set up to<br />

process incoming messages and errors, and communication with the page is handled with a call to<br />

postMessage.<br />

To complete the communication between the page and the Web Worker, first, add the call to<br />

postMessage; for example, inside a messageHandler function:<br />

function messageHandler(e) {<br />

postMessage("worker says: " + e.data + " too");<br />

}<br />

Next, add an event listener to the Web Worker JavaScript file that handles messages coming from<br />

the main page:<br />

addEventListener("message", messageHandler, true);<br />

In this example, the messageHandler function is called immediately when the message is received so<br />

that the message can be echoed back.<br />

Handling Errors<br />

Unhandled errors in an <strong>HTML</strong>5 Web Worker script fire error events on the Web Worker object. Listening<br />

for these error events is especially important when you are debugging scripts that make use of Web<br />

Workers. The following shows an example of an error handling function in a Web Worker JavaScript file<br />

that logs errors to the console:<br />

function errorHandler(e) {<br />

console.log(e.message, e);<br />

}<br />

To handle the errors, you must add an event listener to the main page:<br />

worker.addEventListener("error", errorHandler, true);<br />

197

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

Saved successfully!

Ooh no, something went wrong!