DEV Community

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

 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited

I think this conversation is going in circles.

To reiterate:

  • A simple readystatechange event listener can fix the problem where custom elements appear in the HTML sent from the server
  • If you insert them using JavaScript, you can populate them before insertion
  • If you need to insert elements after connecting to the DOM, you need the sledge hammer

Most of your post makes perfect sense, but towards the end you start to consider a weird case that I don't exactly get where you insert a custom element from client-side code, but you talk about it like DOM parsing is still a factor here, which I don't understand how that would be the case.

Going back to the code in my original comment:

connectedCallback() {
   if (document.readyState === "loading") {
      return document.addEventListener("readystatechange", this.connectedCallback, {once: true})
   }
}
Enter fullscreen mode Exit fullscreen mode

and the example you provided

const body = document.body;
body.addEventListener("click", (evt) => {
   body.append( document.createElement("my-cool-component") );
}
Enter fullscreen mode Exit fullscreen mode

Maybe you could explain what would have to happen for this to fail? There's no child-elements being added to the component in your example, so I don't see where the problem is supposed to come from.

Thread Thread
 
dannyengelman profile image
Danny Engelman • Edited

Yes, that is a a wrong answer in my comment, I re-read the blog post; looks fine to me.

I added a better reply to your readystatechange .

Full working (and readystatechange failing) JSFiddle is: jsfiddle.net/WebComponents/d9sbzcex/

Note: As I said in the blog, WebReflection wrote a parsedCallback that fires when all child Nodes are available.
github.com/WebReflection/html-pars...
It uses the document readyState, MutationObserver and lost more MJ... and is 77 lines of code

The one liner setTimeout will get you the next N Child Nodes

N can be scary for developers who only believe in digital 0 and 1 values, and can't deal with quarks or Schrodingers cat when programming.