การสอน HTML

Page 222

W EB W ORKERS

a task takes a long time, we force the user to wait until the task has finished. Web Workers solve this problem by creating a simple way to write concurrent programs. If we have a script called worker.js that does some image processing, we can invoke it like this: Download webworkers/application.js

var worker = new Worker("worker.js" );

Any JavaScript file can be launched as a worker, but in order for the worker to be independent, your worker script can’t access the DOM. That means you can’t manipulate elements directly. Our main script can send messages to the worker script using postMessage( ) like this: Download webworkers/application.js

$("#button" ).click(function(event){ $("#output" ).html("starting..." ); worker.postMessage("start" ); });

Our worker script can then send messages back to the main page, also using the postmessage( ) method. Download webworkers/worker.js

onmessage = function(event) { if(event.data === "start" ){ // this loop counts. Do something awesome instead. for (var x = 1; x <= 100000; x++){ postMessage(x); } } };

We respond to those events by listening to the onmessage event in our main script. Every time the worker posts back, this code will fire: Download webworkers/application.js

worker.onmessage = function(event){ $("#output" ).html(event.data); }

This API works just like the API for cross-domain messaging, which we talked about in Talking Across Domains, on page 200. There’s no support for Web Workers in Internet Explorer, so you’d need to rely on

Report erratum this copy is (P1.0 printing, December 2010)

222


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.