Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@stefanw
Created July 3, 2010 22:16
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanw/462880 to your computer and use it in GitHub Desktop.
Save stefanw/462880 to your computer and use it in GitHub Desktop.
/* 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);
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment