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.

194<br />

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

Browser Support for <strong>HTML</strong>5 Web Workers<br />

Browser support for Web Workers is at varying stages and will continue to evolve. As shown in Table 8-1,<br />

Web Workers is already supported in many browsers at the time of this writing.<br />

Table 8-1. Opera Supported in version 10.6 and greater<br />

Browser Details<br />

Chrome Supported in version 3 and greater<br />

Firefox Supported in version 3.5 and greater<br />

Internet Explorer Not supported (yet)<br />

Opera Supported in version 10.6 and greater<br />

Safari Supported in version 4 and greater<br />

Using the <strong>HTML</strong>5 Web Workers API<br />

In this section, we’ll explore the use of the Web Workers API in more detail. For the sake of illustration,<br />

we’ve created a simple browser page: echo.html. Using Web Workers is fairly straightforward—you<br />

create a Web Worker object and pass in a JavaScript file to be executed. Inside the page you set up an<br />

event listener to listen to incoming messages and errors that are posted by the Web Worker and if you<br />

want to communicate from the page to the Web Worker, you call postMessage to pass in the required<br />

data. The same is true for the code in the Web 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 />

Checking for Browser Support<br />

Before you call the Web Workers API functions, you will want to make sure there is support in the<br />

browser for what you’re about to do. This way, you can provide some alternate text, prompting the users<br />

of your application to use a more up-to-date browser. Listing 8-1 shows the code you can use to test for<br />

browser support.<br />

Listing 8-1. Checking for browser support<br />

function loadDemo() {<br />

if (typeof(Worker) !== "undefined") {<br />

document.getElementById("support").inner<strong>HTML</strong> =<br />

"Excellent! Your browser supports <strong>HTML</strong>5 Web Workers";<br />

}<br />

}

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

Saved successfully!

Ooh no, something went wrong!