The connectedCallback runs on the opening tag; so its innerHTML is not defined yet. querySelector on this lightDOM will return undefined values.
Your code only works because it defines the component after DOM is created.
What do you mean by this? I think I may have misunderstood the lifecycle methods.
You want your components as self contained as possible
I went this approach to showcase different ways to author the component (creating elements with JavaScript and progressively enhancing with JavaScript). In this context there isn't too much benefit with the progressive enhancement approach, so your refactored version works great.
Good shout on the shadom DOM approach too. That's what I'm working on now for the follow up post.
bloated addEventListener()
Why do you think addEventListener is bloated? My understanding was that it's just a declarative alternative to overriding the onclick property. I couldn't find any documentation on this to suggest there might be a performance impact.
Online since 1990 Yes! I started with Gopher. I do modern Web Component Development with technologies supported by **all** WHATWG partners (Apple, Google, Microsoft & Mozilla)
addEventListener doesn't override/write onclick. It is bloated because using onclick is shorter.
Use the ones that do the job for you: javascript.info/introduction-brows...
What do you mean by this? I think I may have misunderstood the lifecycle methods.
I went this approach to showcase different ways to author the component (creating elements with JavaScript and progressively enhancing with JavaScript). In this context there isn't too much benefit with the progressive enhancement approach, so your refactored version works great.
Good shout on the shadom DOM approach too. That's what I'm working on now for the follow up post.
Why do you think
addEventListener
is bloated? My understanding was that it's just a declarative alternative to overriding theonclick
property. I couldn't find any documentation on this to suggest there might be a performance impact.connectedCallback
Update: see long read Dev.to post: Developers do not connect with the connectedCallback (yet)
Experience yourself; FOO is NOT logged to the console, BAR is logged
Because
connectedCallback()
is executed on the OPENING tag (and when DOM nodes are moved around!)So for component1
this.innerHTML
is referencing DOM that does not exist/isn't parsed yet.Many developers, even libraries that make programming Web Components "easier", do
<script defer src="...">
to force all their components to load like component 2They don't understand the behavior, thus use
defer
. They probably use!important
as well when they do not understand CSS Specificity.LifeCycle Methods:
andyogo.github.io/custom-element-r...
Event listeners
addEventListener
doesn't override/writeonclick
. It is bloated because usingonclick
is shorter.Use the ones that do the job for you: javascript.info/introduction-brows...
Thank you! I'll check it out