Web Components - Hello World
Deatils
- This is a basic example 'Hello, World' example of web components. Some of the examples I've seen make it look much more complicated than it really is.
- The example below is built directly from the HTML and JavaScript code snippets that follow
Example
HTML
<hello-component></hello-component>
JavaScript
class HelloComponent extends HTMLElement {
constructor() {
super()
this.attachShadow({ mode: 'open' })
const wrapper = document.createElement('span')
wrapper.innerText = 'Hello, Component!'
this.shadowRoot.append(wrapper)
}
}
customElements.define('hello-component', HelloComponent)
Notes
- I had to use both the open and close tags explictly. If I tried with the single tag version (i.e. `<hello-component />) the rest of the content on the page disappeared
- Something to research: I'm assuming you have to load these before trying to use them with a tag so you can't put them after a DOM Loaded listener
References