Skip to content

Instantly share code, notes, and snippets.

@damky
Created January 19, 2022 18:39
Show Gist options
  • Save damky/18fc109b2e543eae7732aafa22899a1a to your computer and use it in GitHub Desktop.
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
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