I've created a native Web Component (HTMLElement) and I am using it to expose an otherwise existing component (lowercase 'c') that is a fragment comprised of HTML/CSS/JS ... basically wrapping it in Web Component to help with its re-use and isolate it from the rest of a Web page.
The problem is the component i'm including in my Web Component has some JavaScript to lazy load images, and it lists for the DOMContentLoaded
document event to trigger some of its JS which manipulates the DOM (injects the proper <img>
tag) ..
I am able to get everything into my Web Component, and execute the component's JS within the shadowRoot
(with mode: open
) however the component's event listeners on DOMContentLoaded
are never invoked.
I tried writing everything in my Web Component in both the constructor()
as well as connectedCallback()
but they acted the same.
document...
does that event listener apply only to the ShadowDOM? Or is that actually being bound to parent DOM?UPDATE: I am loading my Web Component asychronously - so it's loaded after the parent's natural DOMContentLoaded event triggers.
No, there is no DOMContentLoaded
Event for the Web Component.
connectedCallback
triggers when the Web Component is injected(connected) into the DOM.
Yes, you can bind Events anywhere in the DOM and have access to everything in the DOM
(when using shadowDOM, that is one of the main differences with IFrames.. which can't access its "container")
Notes:
By your description, it sounds like DOMContentLoaded
has passed; thus I presume you are defining Web Component late (are you loading scripts async
?)
IF you create/load your Web Component ASAP synchronously (or define as a script in the head)
you can catch the DOMContentLoaded
Event
But in general you shouldn't count on that behaviour as the user/developer is/should be in control on when scripts/components load.
The connectedCallback
triggers on the opening tag of your Web Component. If the Web Component was defined early The DOM after the opening tag will not have been parsed yet.
Many libraries like Lit and Hybrids and Stencil provide methods like onUpdated
that "help" or "prevent" you making mistakes ... you are learning a Tool, not the Technology.
In vanilla JS you have to create that behaviour yourself; easily done by adding a 0ms setTimeOut
inside your connectedCallback
. That effectifly waits till the EventLoop is empty and triggers when all DOM is parsed.
FireFox fired connectedCallback
late for a long time, they fixed it March 2021
Long explanation: wait for Element Upgrade in connectedCallback: FireFox and Chromium differences