Kevnz
9/19/2012 - 4:56 AM

Extend function prototype to run a function as a WebWorker

Extend function prototype to run a function as a WebWorker

Function.prototype.runOnBackgroundThread = function (aCallback) {
  var _blob = new Blob(['onmessage = '+this.toString()],{"type":"text/javascript"});
  var _worker = new Worker((webkitURL.createObjectURL || URL.createObjectURL)(_blob));
  _worker.onmessage = aCallback;
  _worker.postMessage();
}

var _test = function () {
  postMessage((1+1).toString());
}

_test.runOnBackgroundThread(function(e){
  alert(e.data);
});