Web Workers in HTML5
Join the DZone community and get the full member experience.
Join For Freedo these application demands sound familiar?
- using background i/o operations
- web services polling
- processing large amount of data
- running an algorithm in the background
- more
if you are working in windows environment you will probably use a background worker (or another thread) for achieving these demands in order to make your application more responsive. in web environment this was impossible since javascript is a single threaded environment. you couldn’t run multiple scripts simultaneously but you could make hacks by using functions like setinterval. in html5 a new api is currently developed in order to enable web applications to run background scripts. in this post i’m going to explain this api – web workers – and to show you how you can use them today with most of the major browsers (not including ie9).
what are web workers?
web workers api is being developed currently. the web workers are background workers that run scripts in parallel to their main page. the web worker itself is independent of any user interface scripts. they allow thread-like operations on the client side that include message-passing mechanism for coordination or data retrieval. if you expected to have a long-lived process, to have a high start-up performance cost, and a high per-instance memory cost web workers can be a good solution.
how to use web workers api?
the specification for web workers specify two kinds of workers – dedicated workers and shared workers. the first kind wraps a given task and perform it. the second can have multiple connections and uses ports for posting messages.
the first thing to do in order to use the web workers api is to create the worker and pass it an execution script url. here is an example for how to do that with dedicated workers:
var worker = new worker('worker.js');
in shared web workers you will create a sharedworker object instead of worker object:
var worker = new sharedworker('worker.js');
when you create a web worker it exposes the following events which help the main page to communicate with the worker:
- onerror – signals that an error occurred in the worker
- onmessage – enables to receive worker messages back in the main page. those messages are raised by the postmessage inner worker event
also, the worker exposes the following inner functions:
- terminate – stops the worker’s execution
- postmessage – posts a message for the listeners of the onmessage event in the main page
in shared web workers you have an addition inner event – onconnect and also the port object. i won’t discuss shared web workers so you can read about them in the web workers current draft . after we understand a little bit about what are web workers and their api lets look at an example.
web workers example
the following example shows how to create a web worker and run it in order to call a simple echo web service.
the service echo the data it receives and its implementation looks like:
[webservice(namespace = "http://tempuri.org/")] [webservicebinding(conformsto = wsiprofiles.basicprofile1_1)] [system.componentmodel.toolboxitem(false)] [scriptservice] public class echoservice : webservice { [webmethod] public string echo(string msg) { return msg; } }
the only interesting thing here is the scriptservice attribute that enables client scripts to call the service.
next lets look at the worker.js file:
var xhr; function getdata(url, params) { try { xhr = new xmlhttprequest(); xhr.open('post', url, false); xhr.setrequestheader("content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function () { if (xhr.readystate == 4) { if (xhr.status == 200) { postmessage(xhr.responsetext); } } }; xhr.send(params); } catch (e) { postmessage('error occured'); } } function callwsmethod() { getdata("http://localhost:30051/webworkers/echoservice.asmx/echo?msg=hello", "msg=hello"); } callwsmethod();
in the worker’s script there are two functions. the first function (getdata) is used to make the request to the service and to post messages back to the main page when the data returns from the service. the second function (callwsmethod) just call the first function with some test data.
the last piece of code is the main page itself:
<!doctype html> <html> <head> <title>worker example: simple ajax call</title> </head> <body> <p> result: <output id="result"> </output></p> <script type="text/javascript"> var worker = new worker('worker.js'); worker.onmessage = function (event) { document.getelementbyid('result').innerhtml = event.data; }; </script> </body> </html>
as you can see the web worker is being created by using the worker.js
file and a handler is wire to the onmessage event. the handler inserts
the data returned by the postmessage function (that exists inside the
worker.js) into an output element (a new html5 element for outputs). you
can try this example on chrome and then you’ll get the following
result:
this is a very simple example and you can start thinking how to take this api to the next level in order to do more interesting things.
summary
lets sum up, web workers api enables the creation of background scripts which can communicate with the main page. this ability is very powerful and can help web developers to create more responsive ui and to achieve things that couldn’t be achieved in web applications in the past. currently web workers are only a draft but there are browsers that support them currently such as chrome, firefox and opera. for further details about web workers you can read the web workers current draft .
source: http://blogs.microsoft.co.il/blogs/gilf/archive/2011/04/08/web-workers-in-html5.aspx
Opinions expressed by DZone contributors are their own.
Comments