DEV Community

Discussion on: Web Component developers do not connect with the connectedCallback (yet)

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

That isn't my work-around though. Here's what that should look like:

customElements.define("your-component", class extends BaseClass {
    connectedCallback() {
        if (document.readyState === "loading") {
            return document.addEventListener("readystatechange", this.connectedCallback.bind(this), {once: true})
        }
        LOG("Access", this); // Hello World!
    }
});
Enter fullscreen mode Exit fullscreen mode

When the component is loaded before the DOM is fully loaded, it will defer its connectedCallback to the next readystatechange event by attaching an event listener and returning early, but when the DOM has already loaded, it will jump over the early return and do its initialisation as usual.

This works in all three cases:

  • When the component is defined before the DOM finishes loading (via the event handler)
  • When the component is defined after the DOM finishes loading (skipping the early return)
  • When the component is inserted via javascript (again, skipping the early return)