-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added function to wait until element appears in DOM
- Loading branch information
1 parent
a5d7207
commit 79dea70
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
})(); | ||
} |