Unfortunately, this feature is only selected in several browsers, namely, IE 10, Firefox (since 3.6), Safari (since 4.0), Chrome & Opera 11.
Some snippets below:
/* Checking if Web Workers are supported by the browser */ if (window.Worker) { // Code using the Web Workers }
The sample test page is found here.
The following is from the article. Read the article for the full explanation and detail:
You’ll then start the worker (and thus a thread under Windows) by sending it a first message:
myHelloWorker.postMessage();Indeed, the Web Workers and the main page are communicating via messages. Those messages can be formed with normal strings or JSON objects. To illustrate simple messages posting, we're going to start by reviewing a very basic sample. It will post a string to a worker that will simply concatenate it with something else. To do that, add the following code into the “helloworker.js” file:
function messageHandler(event) {
// Accessing to the message data sent by the main page
var messageSent = event.data;
// Preparing the message that we will send back
var messageReturned = "Hello " + messageSent + " from a separate thread!";
// Posting back the message to the main page
this.postMessage(messageReturned);
}
// Defining the callback function raised when the main page will call us
this.addEventListener('message', messageHandler, false);
We’ve just defined inside “helloworkers.js” a piece of code that will be executed on another thread. It can receive messages from your main page, do some tasks on it and send a message back to your page in return. We then need to write the receiver in the main page. Here is the page that will handle that:
<!DOCTYPE html>
<html>
<head>
<title>Hello Web Workers<title>
</head>
<body>
<div id="output">div>
<script type="text/javascript">
// Instantiating the Worker
var myHelloWorker = new Worker('helloworkers.js');
// Getting ready to handle the message sent back
// by the worker
myHelloWorker.addEventListener("message", function (event) {
document.getElementById("output").textContent = event.data;
}, false);
// Starting the worker by sending a first message
myHelloWorker.postMessage("David");
// Stopping the worker via the terminate() command
myHelloWorker.terminate();
</script>
</body>
</html>
The result will the be: “Hello David from a separate thread!”. You’re now impressed, aren’t you? The worker will live until you kill it. Beware of that. As they are not automatically garbage collected, it’s up to you to control their states. Moreover, keep in mind that instantiating a worker will have some memory cost and don’t negligate the cold start time neither. To stop a worker, there are 2 possible solutions:
1 – from the main calling page by calling the terminate() command.
2 – from the worker itself via the close() command.
DEMO: You can test this slightly enhanced sample in your browser here ->
http://david.blob.core.windows.net/html5/HelloWebWorkers_EN.htm <-
Posting messages using JSON
Of course, most of the time we will send some more structurated data to the workers. By the way, Web Workers can also communicate between each others using Message channels.But the only way to send some structurated messages to a worker is to use the JSON format. Hopefully, browsers that currently support Web Workers are nice enough to also natively support JSON. How kind they are!
Let’s then take our previous code sample. We’re going to add an object of type WorkerMessage. This type will be used to send some commands with parameters to our Web Workers.
Let’s use now the following simplified HelloWebWorkersJSON_EN.htm web page:
Hello Web Workers JSON
We’re using here the Unobtrusive JavaScript approach which helps us dissociating the view from the attached logic. The attached logic is then living inside this HelloWebWorkersJSON_EN.js file:// HelloWebWorkersJSON_EN.js associated to HelloWebWorkersJSON_EN.htm
// Our WorkerMessage object will be automatically
// serialized and de-serialized by the native JSON parser
function WorkerMessage(cmd, parameter) {
this.cmd = cmd;
this.parameter = parameter;
}
// Output div where the messages sent back by the worker will be displayed
var _output = document.getElementById("output");
/* Checking if Web Workers are supported by the browser */
if (window.Worker) {
// Getting references to the 3 other HTML elements
var _btnSubmit = document.getElementById("btnSubmit");
var _inputForWorker = document.getElementById("inputForWorker");
var _killWorker = document.getElementById("killWorker");
// Instantiating the Worker
var myHelloWorker = new Worker('helloworkersJSON_EN.js');
// Getting ready to handle the message sent back
// by the worker
myHelloWorker.addEventListener("message", function (event) {
_output.textContent = event.data;
}, false);
// Starting the worker by sending it the 'init' command
myHelloWorker.postMessage(new WorkerMessage('init', null));
// Adding the OnClick event to the Submit button
// which will send some messages to the worker
_btnSubmit.addEventListener("click", function (event) {
// We're now sending messages via the 'hello' command
myHelloWorker.postMessage(new WorkerMessage('hello', _inputForWorker.value));
}, false);
// Adding the OnClick event to the Kill button
// which will stop the worker. It won't be usable anymore after that.
_killWorker.addEventListener("click", function (event) {
// Stopping the worker via the terminate() command
myHelloWorker.terminate();
_output.textContent = "The worker has been stopped.";
}, false);
}
else {
_output.innerHTML = "Web Workers are not supported by your browser. Try with IE10: download the latest IE10 Platform Preview";
}
At last, here is the code for the web worker contained in helloworkerJSON_EN.js the file:
function messageHandler(event) {
// Accessing to the message data sent by the main page
var messageSent = event.data;
// Testing the command sent by the main page
switch (messageSent.cmd) {
case 'init':
// You can initialize here some of your models/objects
// that will be used later on in the worker (but pay attention to the scope!)
break;
case 'hello':
// Preparing the message that we will send back
var messageReturned = "Hello " + messageSent.parameter + " from a separate thread!";
// Posting back the message to the main page
this.postMessage(messageReturned);
break;
}
}
// Defining the callback function raised when the main page will call us
this.addEventListener('message', messageHandler, false);
Once again, this sample is very basic. Still, it should help you to understand the underlying logic. For instance, nothing prevents you to use the same approach to send to a worker some gaming elements that will be handled by an AI or physics engine.
No comments:
Post a Comment