Skip to content

Instantly share code, notes, and snippets.

@ever-dev
Created June 14, 2022 15:36
Show Gist options
  • Save ever-dev/1d21ec0b39dc37edb35740de1b2fb67b to your computer and use it in GitHub Desktop.
Save ever-dev/1d21ec0b39dc37edb35740de1b2fb67b to your computer and use it in GitHub Desktop.
Wait for element to be loaded using MutationObserver
function waitForElementLoad(selector) {
return new Promise((resolve, reject) => {
let el = document.querySelector(selector);
if (el) {
resolve(el);
return;
}
new MutationObserver((mutationRecords, observer) => {
// Query for elements matching the specified selector
Array.from(document.querySelectorAll(selector)).forEach(element => {
resolve(element);
//Once we have resolved we don't need the observer anymore.
observer.disconnect();
});
}).observe(document.documentElement, {
childList: true,
subtree: true,
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment