blob: ee6a51fe764674640b32d92b149a0b1fd5073aba (
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
|
type ObserveDOMCallback = () => boolean;
const callbacks: ObserveDOMCallback[] = [];
/**
* 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())
callbacks.splice(i, 1);
if (callbacks.length <= 0) {
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): void {
callbacks.push(callback);
};
|