DEV Community

Discussion on: Web Fundamentals: Web Components Part 1

Collapse
 
dannyengelman profile image
Danny Engelman • Edited

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.

<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