Skip to content

Commit 79dea70

Browse files
committed
Added function to wait until element appears in DOM
1 parent a5d7207 commit 79dea70

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

src/util/waitForElement.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* Waits until Element will appear
3+
* @param {HTMLElement} elSelector Selector to locate Element
4+
* @param {number} timeout Maximum timeout after which Error will be thrown
5+
* @param {() => void} callback Callback to be called after Element appearance
6+
*/
7+
export default function waitForElement(elSelector, callback) {
8+
if (document.querySelector(elSelector) !== null) {
9+
callback();
10+
return;
11+
}
12+
13+
if (typeof MutationObserver !== "undefined") {
14+
/* jshint ignore:start */
15+
const observer = new MutationObserver(() => {
16+
if (document.querySelector(elSelector) !== null) {
17+
observer.disconnect();
18+
callback();
19+
}
20+
});
21+
/* jshint ignore:end */
22+
23+
observer.observe(document.body, {
24+
childList: true,
25+
subtree: true,
26+
attributes: false,
27+
characterData: false,
28+
});
29+
} else {
30+
// Old browsers will wait by timeout
31+
waitForElementByTimeout(elSelector, callback, 1000, 10000);
32+
}
33+
}
34+
35+
/**
36+
* @param {string} elSelector
37+
* @param {() => void} callback
38+
* @param {number} checkInterval In milliseconds
39+
* @param {number} maxTimeout In milliseconds
40+
*/
41+
function waitForElementByTimeout(
42+
elSelector,
43+
callback,
44+
checkInterval,
45+
maxTimeout
46+
) {
47+
let startTimeInMs = Date.now();
48+
(function loopSearch() {
49+
if (document.querySelector(elSelector) !== null) {
50+
callback();
51+
return;
52+
} else {
53+
setTimeout(function () {
54+
if (Date.now() - startTimeInMs > maxTimeout) {
55+
callback();
56+
return;
57+
}
58+
loopSearch();
59+
}, checkInterval);
60+
}
61+
})();
62+
}

0 commit comments

Comments
 (0)