HTML5 and CSS3, Second Edition

(singke) #1
Finally, back in javascripts/application.js, we fill in the onmessage() event handler
and add each result to the page:

where_next/web_workers/javascripts/application.js
worker.onmessage=function(event){
➤ varimg = $("<img>");
➤ varlink= $("<a>");
➤ varresult= event.data;
➤ varwrapper;

➤ link.attr("href", result.videolink);
➤ img.attr("src", result.thumbnail);
➤ link.append(img);
➤ wrapper= link.wrap("<div>").parent();
➤ $("#output").append(wrapper);
};

worker.onerror=function(event){
$("outpout").html("Whydo you fail??");
};

You might have noticed that the API for web workers works just like the API
for cross-domain messaging, which we talked about in Tip 31, Talking across
Domains, on page 213. We get a message from the worker, and we respond to
it. Unfortunately there’s no support for web workers in Internet Explorer
versions lower than 10. But if you’re looking to do some heavier nonblocking
client-side work, you’ll want to look into this further. In this particular
example we could detect for worker support and, if it’s not supported, we
could call a regular JSONP request with jQuery.

Debugging web workers can be tricky. Since we can’t easily access the DOM
and we can’t use console.log(), our only options are to throw exceptions or to
use postMessage() to send data back, then print it to the page in the onmessage()
event handler. These methods are a bit kludgy, but they do work.

Web workers are great for situations where you have long-running and often
CPU-intensive things you need to do without blocking the main user-interface
thread. If your app does some client-side data-crunching, investigate this
further.

11.4 Server-Sent Events


Web sockets are cool, but they require a different protocol and are really
meant for two-way communication. If you just need to push data to the client
from the server, you can use server-sent events, or SSE, which works over
regular old HTTP.

report erratum • discuss

Server-Sent Events • 247


Download from Wow! eBook <www.wowebook.com>

Free download pdf