HTML5 and CSS3, Second Edition

(singke) #1
In this case we’re sending the search term to the worker. The worker can
send us messages back, and we can act on those messages if we listen to the
worker’s onmessage() event:

where_next/web_workers/javascripts/application.js
worker.onmessage=function(event){
};

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

Every time the worker posts back, this code will fire.


So now let’s explore what it takes to make our worker receive and send mes-
sages to the main application. First, the worker itself has an onmessage() event
we need to listen for. When the main script sends messages to the worker,
this code will fire.

where_next/web_workers/javascripts/worker.js
varonmessage=function(event){
varquery= event.data;
getYoutubeResults(query);
};

We pass the search term to our own function called getYoutubeResults(), which
will construct the search query for us and send the search request off to
YouTube. Usually with JSONP, we have to make the request by adding a
<script> tag to the main page. But in a web worker, we don’t have access to
the DOM, the browser window, or anything like that. But we do have the
extremely flexible importScripts() method, which can call local, relative, and
remote URLs.

where_next/web_workers/javascripts/worker.js
var getYoutubeResults=function(searchTerm){
varcallback="processResults";
url ="http://gdata.youtube.com/feeds/videos?vq="+ searchTerm+
"&alt=json-in-script&max-results=5&callback="+ callback;
importScripts(url);
};

This builds up the search URL, passing both the search keyword and the
callback function. All we have to do now is write the callback function called
processResults().

The response from YouTube will look like this, although with a lot more
information:

report erratum • discuss

Web Workers • 245


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

Free download pdf