I am using jQuery JavaScript library. I like the event listener ready on $(document)
that fires when the DOM is set up.
( Pretty similar
jQuery don't have it, but we can create our own onDomElementIsReady, Tools: jQuery
, ES6
, Promise
and Interval
(I'm lazy, but you can get the idea)
We will wait until the element existed on the DOM and as soon is available we will resolve the promise
result.
const onDomElementIsReady = (elementToWatch)=> {
//create promise
return new Promise((res, rej)=> {
let idInterval = setInterval(()=> {
//keep waiting until the element exist
if($(elementToWatch).length > 0) {
clearInterval(idInterval); //remove the interval
res($(elementToWatch)); //resolve the promise
}
},100);
});
};
//how to use it?
onDomElementIsReady(".myElement").then(element => {
//use jQuery element
});
NOTE: To improve this we should add a timer that reject
the promise if the DOM element never exists.