HTML5 and CSS3, Second Edition

(singke) #1
document. The data from YouTube then gets passed to the callback function
we specified. All we have to do is write the callback function to parse the data.
It’s pretty clever and lets us get around that pesky same-origin policy that
browsers have.

Let’s build this out. First we’ll create a pretty standard HTML page:


where_next/web_workers/index.html
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<title>Web Workers</title>
<style>
#output> div{float:left;margin-right:5px;}
</style>
</head>
<body>
<inputtype="button"id="button"value="GetResults">
<divid="output"></div>

<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<scriptsrc="javascripts/application.js"></script>
</body>
</html>

This page loads up jQuery and a script called scripts/application.js, which will do
the basic interaction with the page. We also have a tiny bit of CSS in the
<head> section that will arrange the videos in a grid format.

We’ll have another file, called javascripts/worker.js, that will do the communication
with YouTube. This will be our web worker, and we set it up like this:

where_next/web_workers/javascripts/application.js
varworker=newWorker("javascripts/worker.js");

Any JavaScript file can be launched as a worker, but for the worker to be
independent, the worker script can’t access the Document Object Model
(DOM). That means you can’t manipulate elements directly. But you can pass
data to the worker and get it back later.

Our main script can send messages to the worker script using postMessage(),
like this:

where_next/web_workers/javascripts/application.js
$("#button").click(function(event){
worker.postMessage("pragprog");
});

Chapter 11. Where to Go Next • 244


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf