Skip to content

Commit 5f58f8d

Browse files
gooddaytodaykiselev
authored andcommitted
Added function to wait until element appears in DOM
1 parent a8f9435 commit 5f58f8d

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

src/util/waitForElement.js

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

0 commit comments

Comments
 (0)