Created
January 4, 2021 14:48
-
-
Save cartoonclouds/925bca8019457f8c300ee613c86c676a to your computer and use it in GitHub Desktop.
Util to wait for an element to be added to the DOM before further execution
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
/** Using MutationObserver **/ | |
/*****************************/ | |
/** | |
* Continually searches for an element (by selector) in the DOM and returns it if found. | |
* | |
* @param selector<string> A selector string use to search for the element | |
* @returns {Promise<any>} | |
*/ | |
function existsInDOM(selector) { | |
return new Promise(resolve => { | |
if (document.querySelector(selector)) { | |
return resolve(document.querySelector(selector)); | |
} | |
const observer = new MutationObserver(mutations => { | |
if (document.querySelector(selector)) { | |
resolve(document.querySelector(selector)); | |
observer.disconnect(); | |
} | |
}); | |
observer.observe(document.body, { | |
childList: true, | |
subtree: true | |
}); | |
}); | |
} | |
/** Using setTimeout **/ | |
/***********************/ | |
/** | |
* Continually searches for an element (by selector) in the DOM and returns it if found. | |
* | |
* @param selector<string> This function looks for the element ${selector} | |
* @param checkFrequencyInMs<int> This function checks whether this element exists every ${checkFrequencyInMs} milliseconds | |
* @param timeoutInMs<int> This function stops looking for the element after ${timeoutInMs} milliseconds. | |
* @returns {Promise<any>} | |
*/ | |
function existsInDOM(selector, checkFrequencyInMs = 1000, timeoutInMs = 9000) { | |
let startTimeInMs = Date.now(); | |
return new Promise((resolve, reject) => { | |
(function loopSearch() { | |
if (document.querySelector(selector) != null) { | |
return resolve(); | |
} | |
else { | |
setTimeout(function () { | |
if (Date.now() - startTimeInMs > timeoutInMs) { | |
return reject('timeout'); | |
} | |
loopSearch(); | |
}, checkFrequencyInMs); | |
} | |
})(); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment