-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXHRWatcher.js
48 lines (38 loc) · 961 Bytes
/
XHRWatcher.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
const EventEmitter = require('events');
module.exports = class XHRWatcher extends EventEmitter {
constructor() {
super();
this.queue = new Set();
}
install(window) {
const watcher = this;
class WrappedXMLHttpRequest extends window.XMLHttpRequest {
constructor() {
super();
watcher.watch(this);
}
}
window.XMLHttpRequest = WrappedXMLHttpRequest;
}
watch(xhr) {
xhr.addEventListener("loadstart", () => this.handleLoadStart(xhr));
xhr.addEventListener("loadend", () => this.handleLoadEnd(xhr));
}
handleLoadStart(xhr) {
this.queue.add(xhr);
}
handleLoadEnd(xhr) {
this.queue.delete(xhr);
if (this.allDone)
this.emit('queueEmpty');
}
get allDone() {
return this.queue.size === 0;
}
untilDone() {
return new Promise((resolve, reject) => {
if (this.allDone) resolve();
else this.on('queueEmpty', () => { resolve(); });
});
}
}