Web Components

Web components came up in a chat yesterday so I looked into it today. They work in modern browsers now.

Basically, a custom component lets you use your own element like this:

<cat-card
    name="Alice"
    img="https://placekitten.com/250/249"
></cat-card>

With JavaScript like this:

class Cat extends HTMLElement {
    constructor() {
        super();

        const shadow = this.attachShadow({ mode: "open" });

        // The wrapper for the element
        const wrapper = document.createElement("div");
        wrapper.setAttribute("class", "wrapper");

        // Create the header
        const header = document.createElement("h2");
        header.setAttribute("class", "header");
        header.textContent = this.getAttribute("name");

        // Create the image
        const img = document.createElement("img");
        img.setAttribute("class", "img");
        img.src = this.hasAttribute("img")
            ? this.getAttribute("img")
            : "https://placekitten.com/250/250";

        // Create the styles
        const style = document.createElement("style");
        style.textContent = `
            .wrapper {
                border: solid 1px #eee;
                box-shadow: 0 0 7px 1px #eee;
                border-radius: 5px;
                padding: 21px;
            }
            .img {
                border-radius: 5px;
                margin: 0 auto;
            }
        `;

        // Add to shadow DOM
        shadow.appendChild(style);
        shadow.appendChild(wrapper);
        wrapper.appendChild(header);
        wrapper.appendChild(img);
        console.log("here's the element", wrapper.outerHTML);
    }
}

// Element names require a dash.
customElements.define("cat-card", Cat);

I haven’t looked into it very closely yet, but the full documentation is here:

https://developer.mozilla.org/en-US/docs/Web/Web_Components

1 Like

Cat Stevens.

Sidenote: is there a cooler programming term than “shadow DOM?”

2 Likes

I found a page on web component libraries, including hybrids, Stencil.js, and lit-element/lit-html.

It looks like they can also be used with older frameworks Vue and React, as well as Angular too (like you mentioned).

Sounds a whole lot like Polymer Elements, to be honest. Hopefully this doesn’t come with the bloat that Google brought to the table.

Hell no! Shadow DOM is the bomb! :slight_smile:

This article series on codepen is also good: https://css-tricks.com/an-introduction-to-web-components/