/
worker.js
60 lines (57 loc) · 1.33 KB
/
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
53
54
55
56
57
58
59
60
importScripts('../esm/server.js')
const isServiceWorker = 'clients' in self;
const clients = [];
// Example: ServiceWorker interaction
if (isServiceWorker)
addEventListener('activate', event => {
event.waitUntil(clients.claim());
});
// SharedWorker fallback
else
addEventListener('connect', ({source}) => {
clients.push(source);
});
ProxiedWorker({
test: 'OK',
sum(a, b) {
return a + b;
},
on(type, cb) {
setTimeout(cb, 500, type);
},
notify() {
setTimeout(
async () => {
console.log('notifying');
const data = {id: 'notify', args: [1, 2, 3]};
// ServiceWorker claimed clients
if (isServiceWorker) {
for (const client of await self.clients.matchAll({type: 'all'}))
client.postMessage(data);
}
// SharedWorker claimed clients
else if (clients.length) {
for (const client of clients)
client.postMessage(data);
}
// Worker fallback
else
postMessage(data);
},
1000
);
},
async delayed() {
console.log('context', this.test);
return await new Promise($ => setTimeout($, 500, Math.random()));
},
Class: class {
constructor(name) {
this.name = name;
}
sum(a, b) {
console.log(this.name, a, b);
return a + b;
}
}
});