forked from inexorabletash/polyfill
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathworkers.js
112 lines (96 loc) · 2.94 KB
/
workers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
//
// Web Workers (http://www.whatwg.org/specs/web-workers/current-work/)
//
window.Worker = window.Worker || (function () {
function __loadScript(src, callback, errback) {
var HTTP_OK = 200,
FILE_OK = 0,
xhr = new XMLHttpRequest(),
async = true;
xhr.open("GET", src, async);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (status === FILE_OK || status === HTTP_OK) {
callback(xhr.responseText);
}
else if (errback) {
errback(xhr.responseText);
}
}
};
xhr.send(null);
}
function Worker(src) {
//--------------------------------------------------
// Environment exposed to the worker script
//--------------------------------------------------
var worker = this,
onmessage = null, // set by worker, called on post by parent
__tasks = [], // queue of messages from parent
__closing = false; // flag, set when closing
//--------------------------------------------------
// API exposed from the Worker object
//--------------------------------------------------
// set by parent, called on post by worker
worker.onmessage = null;
// set by parent, called on post by worker
worker.onerror = null;
// post message to the worker
worker.postMessage = function (message) {
if (__closing) { return; }
__tasks.push(setTimeout(function () {
try {
if (typeof onmessage === 'function') {
onmessage({ data: message });
}
}
catch (e) {
if (typeof worker.onerror === 'function') {
worker.onerror(e);
}
}
}, 0));
};
// terminate the worker
worker.terminate = function () {
__closing = true;
while (__tasks.length) {
clearTimeout(__tasks.shift());
}
};
//--------------------------------------------------
// API exposed to the worker script
//--------------------------------------------------
var workerContext = {
// post message from the worker to the parent
postMessage: function(message) {
setTimeout(function () {
if (typeof worker.onmessage === 'function') {
worker.onmessage({ data: message });
}
}, 0);
},
// discard tasks and prevent further task queueing
close: function() {
worker.terminate();
},
importScripts: function(urls) {
var i;
for (i = 0; i < arguments.length; i += 1) {
__loadScript(src, function (script) {
eval(script);
}, function (error) {
throw Error(error);
});
}
}
};
workerContext.self = workerContext;
__loadScript(src, function (script) {
with (workerContext) {
eval("(function(){" + script + "}).call(workerContext)");
}
});
};
return Worker;
} ());