Skip to content

Commit

Permalink
Added function to wait until element appears in DOM
Browse files Browse the repository at this point in the history
  • Loading branch information
gooddaytoday committed May 30, 2022
1 parent a5d7207 commit 79dea70
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions src/util/waitForElement.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/**
* Waits until Element will appear
* @param {HTMLElement} elSelector Selector to locate Element
* @param {number} timeout Maximum timeout after which Error will be thrown
* @param {() => void} callback Callback to be called after Element appearance
*/
export default function waitForElement(elSelector, callback) {
if (document.querySelector(elSelector) !== null) {
callback();
return;
}

if (typeof MutationObserver !== "undefined") {
/* jshint ignore:start */
const observer = new MutationObserver(() => {
if (document.querySelector(elSelector) !== null) {
observer.disconnect();
callback();
}
});
/* jshint ignore:end */

observer.observe(document.body, {
childList: true,
subtree: true,
attributes: false,
characterData: false,
});
} else {
// Old browsers will wait by timeout
waitForElementByTimeout(elSelector, callback, 1000, 10000);
}
}

/**
* @param {string} elSelector
* @param {() => void} callback
* @param {number} checkInterval In milliseconds
* @param {number} maxTimeout In milliseconds
*/
function waitForElementByTimeout(
elSelector,
callback,
checkInterval,
maxTimeout
) {
let startTimeInMs = Date.now();
(function loopSearch() {
if (document.querySelector(elSelector) !== null) {
callback();
return;
} else {
setTimeout(function () {
if (Date.now() - startTimeInMs > maxTimeout) {
callback();
return;
}
loopSearch();
}, checkInterval);
}
})();
}

0 comments on commit 79dea70

Please sign in to comment.