JSFiddle - React, Tailwind, and code Playground
HTML
<div id="output"></div>
JavaScript
//Please note: this will work in most browsers which do not have web worker support, because the library falls back to a single thread.
//Minimum test case (works in chrome, firefox)
var test = new Ozai({
fn: function (a,b,cb) {
cb(a + " + " + b + " = " + (a + b));
}
});
test.fn(100, 200, function(sum) {
document.getElementById("output").textContent = sum;
});
//Below is the library I am working on to create the web worker
function Ozai (obj) {
var worker;
var self = this;
/* Thank you, broofa.
* http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript */
function makeID () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
function createObjectURL (file) {
if (window.webkitURL) {
return window.webkitURL.createObjectURL(file);
} else if (window.URL && window.URL.createObjectURL) {
return window.URL.createObjectURL(file);
} else {
return null;
}
}
function __init__ () {
//build the worker script node
var workerScript =
"scopeObj = {}; \
\nself.onmessage = function(e) { \
\n var msg = e.data; \
\n var id = msg.id; \
\n var fn = msg.fn; \
\n var args = msg.args \
\n .concat([ function() { \
\n self.postMessage({args: Array.prototype.slice.call(arguments, 0), id: id}); \
\n }]); \
\n scopeObj[fn].apply(scopeObj,args); \
\n}";
//create functions for this thread to call
var isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
for(var i in obj) {
if(isFunction(obj[i]))
workerScript += "\nscopeObj['" + i + "'] = " + obj[i].toString();
else
workerScript += "\nscopeObj['" + i + "'] = " + JSON.stringify(obj[i]);
}
//create worker from script node
if(window.Worker) {
...