Skip to content

Instantly share code, notes, and snippets.

@d1manson
Last active June 27, 2018 11:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d1manson/7722426 to your computer and use it in GitHub Desktop.
Save d1manson/7722426 to your computer and use it in GitHub Desktop.
Using an HTML5 Blob, you can get around the same-origin security restriction for Web Workers. The only slight complication is the need to return a Worker-like interface synchrounously. But this is actually fairly simple. Requires jQuery $ for ajax call. IE doesn't permit making workers from blob-urls, but other browsers do.
Worker = (function(){
var nativeWorker = Worker;
var BlobWorker = function(){
this.queuedCallList = [];
this.trueWorker = null;
this.onmessage = null;
}
BlobWorker.prototype.postMessage = function(){
if(this.trueWorker)
this.trueWorker.postMessage.apply(this,arguments);
else
this.queuedCallList.push(['postMessage',arguments]);
};
BlobWorker.prototype.terminate = function(){
if(this.trueWorker)
this.trueWorker.terminate();
else
this.queuedCallList.push(['terminate',arguments]);
}
BlobWorker.prototype.FileDataReceived = function(script){
this.trueWorker = new nativeWorker(window.URL.createObjectURL(new Blob([script],{type:'text/javascript'})));
if(this.onmessage)
this.trueWorker.onmessage = this.onmessage;
while(this.queuedCallList.length){
var c = this.queuedCallList.shift();
this.trueWorker[c[0]].apply(this.trueWorker,c[1]);
}
}
return function(url){
var w = new BlobWorker();
$.ajax(url,{
success: $.proxy(w.FileDataReceived,w),
error: function(s,err){throw err},
dataType:"text"});
return w;
};
})();
@d1manson
Copy link
Author

It will be necessary to inject some similar code into the worker's script if the worker wants to spawn subworkers...you can just add the extra code to the start of the script string in FileDataReceived.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment