public
Last active

  • Download Gist
WorkerFacade.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
/* A facade for the Web Worker API that fakes it in case it's missing.
Good when web workers aren't supported in the browser, but it's still fast enough, so execution doesn't hang too badly (e.g. Opera 10.5).
By Stefan Wehrmeyer, licensed under MIT
*/
 
var WorkerFacade;
if(!!window.Worker && !iCanHasFastBrowser()){
WorkerFacade = (function(){
return function(path){
return new window.Worker(path);
};
}());
} else {
WorkerFacade = (function(){
var workers = {}, masters = {}, loaded = false;
var that = function(path){
var theworker = {}, loaded = false, callings = [];
theworker.postToWorkerFunction = function(args){
try{
workers[path]({"data":args});
}catch(err){
theworker.onerror(err);
}
};
theworker.postMessage = function(params){
if(!loaded){
callings.push(params);
return;
}
theworker.postToWorkerFunction(params);
};
masters[path] = theworker;
var scr = document.createElement("SCRIPT");
scr.src = path;
scr.type = "text/javascript";
scr.onload = function(){
loaded = true;
while(callings.length > 0){
theworker.postToWorkerFunction(callings[0]);
callings.shift();
}
};
document.body.appendChild(scr);
return theworker;
};
that.fake = true;
that.add = function(pth, worker){
workers[pth] = worker;
return function(param){
masters[pth].onmessage({"data": param});
};
};
that.toString = function(){
return "FakeWorker('"+path+"')";
};
return that;
}());
}
 
/* Then just use WorkerFacade instead of Worker (or alias it)
 
The Worker code must should use a custom function (name it how you want) instead of postMessage.
Put this at the end of the Worker:
 
if(typeof(window) === "undefined"){
onmessage = nameOfWorkerFunction;
customPostMessage = postMessage;
} else {
customPostMessage = WorkerFacade.add("path/to/thisworker.js", nameOfWorkerFunction);
}
 
*/

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.