-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoffthread-image-worker.js
52 lines (42 loc) · 1.05 KB
/
offthread-image-worker.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
'use strict';
class ImageHandler {
constructor(workerContext) {
this.queue = [];
this.workerContext = workerContext;
}
enqueue(toEnqueue) {
// Bail if this URL is already enqueued.
if (this.queue.indexOf(toEnqueue) >= 0) {
return;
}
this.queue.push(toEnqueue);
this.resumeQueue();
}
resumeQueue() {
if (this.queue.length === 0) {
return;
}
const data = this.queue.shift();
const blob = data.blob;
createImageBitmap(blob)
.then(imageBitmap => {
this.workerContext.postMessage({
imageBitmap: imageBitmap,
url: data.url,
instanceIndex: data.instanceIndex
}, [imageBitmap]);
}, error => {
this.workerContext.postMessage({
error: error.toString(),
url: data.url,
instanceIndex: data.instanceIndex
});
})
.then(_ => this.resumeQueue())
.catch(_ => this.resumeQueue());
}
}
const handler = new ImageHandler(self);
self.onmessage = (e) => {
return handler.enqueue(e.data);
};