Here is a core JavaScript function to wait for the display of an element (well, its insertion into the DOM to be more accurate).
// Call the below function
waitForElementToDisplay("#div1",function(){alert("Hi");},1000,9000);
function waitForElementToDisplay(selector, callback, checkFrequencyInMs, timeoutInMs) {
var startTimeInMs = Date.now();
(function loopSearch() {
if (document.querySelector(selector) != null) {
callback();
return;
}
else {
setTimeout(function () {
if (timeoutInMs && Date.now() - startTimeInMs > timeoutInMs)
return;
loopSearch();
}, checkFrequencyInMs);
}
})();
}
This call will look for the HTML tag whose id="div1"
every 1000 milliseconds. If the element is found, it will display an alert message Hi. If no element is found after 9000 milliseconds, this function stops its execution.
Parameters:
selector
: String : This function looks for the element ${selector}.callback
: Function : This is a function that will be called if the element is found.checkFrequencyInMs
: Number : This function checks whether this element exists every ${checkFrequencyInMs} milliseconds.timeoutInMs
: Number : Optional. This function stops looking for the element after ${timeoutInMs} milliseconds.NB : Selectors are explained at https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector