DEV Community

Discussion on: Web Fundamentals: Web Components Part 1

Collapse
 
hasanhaja profile image
Hasan Ali

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.

Collapse
 
dannyengelman profile image
Danny Engelman • Edited

connectedCallback

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.

<script>
  class MyBaseClass extends HTMLElement {
    connectedCallback() {
        console.log(this.innerHTML)
    }
  }
  customElements.define("my-component1", class extends MyBaseClass {})
</script>

<my-component1>FOO</my-component1>
<my-component2>BAR</my-component2>

<script>
  customElements.define("my-component2", class extends MyBaseClass {})
</script>
Enter fullscreen mode Exit fullscreen mode

Many developers, even libraries that make programming Web Components "easier", do

<script defer src="..."> to force all their components to load like component 2

They 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/write onclick. It is bloated because using onclick is shorter.
Use the ones that do the job for you: javascript.info/introduction-brows...

Thread Thread
 
hasanhaja profile image
Hasan Ali

Thank you! I'll check it out