HTML5 WebWorkers
Spawning webworkers
- Webworker and page must pass messages (.postMessage(), message event.) Messages can be JSON. No functions or cyclical references.
if (!!window.Worker) {
var worker = new Worker('testworker.js');
//listen for messages from worker
worker.onmessage = function(event) {
console.log(event.data);
};
//listen for worker errors
worker.onerror = function(event) {
console.log(event.message + " in " + event.filename + " at " + event.lineno);
};
//pass json
worker.postMessage({ stop: true });
//if you need, stop the worker
//worker.terminate();
};
Workers
- Worker cannot use UI/DOM. There's no window object, but can use setTimeout, setInterval, XMLHttpRequest (ajax).
- Workers can spawn subworkers in IE, FF but not Chrome
//import scripts (synchronous!)
//NB: JQuery will error as window is undefined
importScripts('testlib.js');
self.postMessage("Starting.");
self.onerror = function (event) {
console.log(event.message);
self.postMessage('Error ' + event.message);
};
self.onclose = function () {
self.postMessage("Closing");
};
self.onmessage = function (event) {
self.postMessage('Got message ' + event.data);
if (event.data.stop) {
self.postMessage("Message to close.");
self.close();
}
};