Async Wait for Element
Need to wait for an element to exist before touching it? setTimeout and mutation observers are overkill for most cases. Here’s a simple async loop that checks for the element and resolves when it’s ready. No dependencies. No noise.
function waitForElement(selector) {
return new Promise(resolve => {
const observer = new MutationObserver(mutations => {
if (document.querySelectorAll(selector)) {
if (document.querySelectorAll(selector).length > 0) {
resolve(document.querySelectorAll(selector));
observer.disconnect();
}
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}