Created
January 19, 2022 18:39
-
-
Save damky/18fc109b2e543eae7732aafa22899a1a to your computer and use it in GitHub Desktop.
Ready function that waits for one or more target elements to be on the page before executing callback function
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 Ready(target, cb) { | |
let observer; | |
const config = { | |
attributes: true, | |
childList: true, | |
subtree: true, | |
characterData: true | |
}; | |
if (!observer) { | |
observer = new MutationObserver(check); | |
observer.observe(document.documentElement, config); | |
check(); | |
} | |
function check() { | |
const element = | |
typeof target === 'object' | |
? (target.every((targetEl) => document.querySelector(targetEl)) && | |
target.map((targetEl) => document.querySelector(targetEl))) || [ | |
null | |
] | |
: [document.querySelector(target)]; | |
if (element.every((el) => !!el) && element.every((el) => !el.ready)) { | |
element.forEach((el) => (el.ready = true)); | |
setTimeout(() => { | |
cb(); | |
}, 50); | |
} | |
} | |
} | |
export default Ready; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment