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.

196<br />

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

Let’s say that you want to build a simple Web Worker example that allows users to send a message to<br />

a worker, which in turn echoes back the message. This example may not be very useful in real life, but<br />

it’s useful enough to explain the concepts you need to build more complex examples.<br />

Figure 8-3 shows this example web page and its Web Worker in action. The code for this simple page is<br />

listed at the end of this section.<br />

Figure 8-3. A simple web page that uses <strong>HTML</strong>5 Web Workers<br />

To set up proper communication with your Web Worker, code has to be added to the main page (the<br />

page that calls the Web Worker) as well as the worker JavaScript file.<br />

Coding the Main Page<br />

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

listen to incoming messages and errors that are sent by the Web Worker to the page, you set up an event<br />

listener.<br />

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

postMessage to the main page, as follows:

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

Saved successfully!

Ooh no, something went wrong!