Last active
June 27, 2018 11:28
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.