How do I delay execution of code inside my web component until the entire document is loaded and ready?
My web component needs to interact with elements outside of itself -- it will query the body
tag for elements, and those those elements will usually appear after the web component in document order. So, the web component will be added to the DOM first.
Sure enough, in connectedCallback
, none of those other elements can be found, I assume because they haven't been added to the DOM yet. If I move my web component lower on the page, it finds them just fine (presumably because they were added before the web component).
I have tried the traditional method of document.addEventListener('DOMContentLoaded', myFunction)
, but the problem is that inside myFunction
, this
now references the HTML document, not my web component. So I'm executing code "outside" the web component, which is not what I want.
How can I do something on DOMContentLoaded
and execute code in the context of my web component? Or how can I otherwise defer execution until the entire DOM has populated, no matter where on the page my web component sits?
add the event listener inside the connectedCallback, alternatively, you "could" use a setTimout( ()=>myfunction, 5000 ) to wait 5 seconds before running. "Hacky" but should work.
class MyCustomWebComponent extends HTMLElement {
constructor() {
super();
}
myFunction(e) {
// do the thing with the body elements
}
connectedCallback() {
document.addEventListener('DOMContentLoaded', (e) => myFunction(e);) // using anonymous function will bind 'this' properly to myFunction
}
}