Last active
December 10, 2015 02:38
-
-
Save tiffon/4368560 to your computer and use it in GitHub Desktop.
Create a WebWorker from a javascript function. Optionally, supply environment variables. Derived from this jsFiddle: http://jsfiddle.net/YUKSu/7/
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
var jsToWorker = (function(win) { | |
var enabled = !!win.Worker, | |
blobBuilder = win.BlobBuilder || win.WebKitBlobBuilder || win.MozBlobBuilder, | |
urlFactory = win.URL || win.webkitURL, | |
stringToBlobUrl; | |
if (!enabled || !urlFactory || (!win.Blob && !blobBuilder)) { | |
var noop = function(){}; | |
noop.enabled = false; | |
noop.jsToBlobUrl = noop; | |
noop.workerFromJs = noop; | |
return noop; | |
} | |
if (blobBuilder) { | |
stringToBlobUrl = function getURLWithBB_(script) { | |
var bb = new blobBuilder(); | |
bb.append(script); | |
return urlFactory.createObjectURL(bb.getBlob()); | |
}; | |
} else { | |
stringToBlobUrl = function getURLWithBlob_(script) { | |
var b = new Blob([script], {type:'text\/javascript'}); | |
return urlFactory.createObjectURL(b); | |
}; | |
} | |
function jsToBlobUrl(script, context) { | |
if (!script) { | |
return; | |
} | |
var typ = typeof script, | |
res = ''; | |
if (typ === 'string' && !script.length) { | |
return; | |
} | |
// if context is an object then stringify, | |
// otherwise it should be a JSON string | |
if (context) { | |
res = '!function(){ var ctx = JSON.parse(\''; | |
if (typeof context === 'object') { | |
res += JSON.stringify(context); | |
} else { | |
res += context; | |
} | |
res += '\');\n for (var p in ctx) { this[p] = ctx[p]; }}();\n'; | |
} | |
// if it's a function, immediately invoke it in the web worker | |
if (typ === 'function') { | |
res += '!' + script + '()'; | |
} else { | |
res += script; | |
} | |
return stringToBlobUrl(res); | |
} | |
function workerFromJs(stringOrFunc, context) { | |
var blobUrl = jsToBlobUrl(stringOrFunc, context); | |
if (blobUrl) { | |
return new Worker(blobUrl); | |
} | |
} | |
var api = function(stringOrFunc, context) { | |
return workerFromJs(stringOrFunc, context); | |
}; | |
api.enabled = true; | |
api.jsToBlobUrl = jsToBlobUrl; | |
api.workerFromJs = workerFromJs; | |
return api; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment