blob: 90a52ffce3b1734773133e687e4fca81ba35f77e (
plain)
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
|
type ObserveDOMCallback = () => boolean;
let callbacks: (ObserveDOMCallback | null)[] = [];
let callbacksCalledCount = 0;
/**
* Starts a MutationObserver on the document that invokes each
* registered callback. A callback should return `true` when it
* has completed its work; once all callbacks are done the observer
* disconnects.
*/
const observer = new MutationObserver(() => {
for (let i = 0; i < callbacks.length; i++) {
const callback = callbacks[i];
if (callback && callback()) {
callbacksCalledCount++;
callbacks[i] = null;
}
if (callbacksCalledCount >= callbacks.length) {
observer.disconnect();
break;
}
}
});
observer.observe(document, {
childList: true,
subtree: true
});
/**
* Registers a callback to run on DOM mutations.
* The callback is invoked on each mutation tick and should return `true`
* when its work is finished. When all callbacks have completed the
* observer stops.
*
* @param callback - Function that returns `true` when done.
*/
export function observeDOM(callback: ObserveDOMCallback) {
callbacks.push(callback);
};
|