Created
June 14, 2022 15:36
-
-
Save ever-dev/1d21ec0b39dc37edb35740de1b2fb67b to your computer and use it in GitHub Desktop.
Wait for element to be loaded using MutationObserver
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
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