DEV Community

Cover image for JS&Friends Conf: Mastering Shadow DOM - Martine Dowden
Adam Romig πŸ‡΅πŸ‡­
Adam Romig πŸ‡΅πŸ‡­

Posted on

JS&Friends Conf: Mastering Shadow DOM - Martine Dowden

Mastering Shadow DOM - Martine Dowden

Martine Dowden

Martine showed us how to create web components using just HTML and vanilla JavaScript - that's right, no framework!

We learned what Web Components and Custom Elements are as well as how the Shadow DOM works to give us the ability for encapsulated reusable components. After reviewing basic DOM manipulation with JavaScript, she showed us how to create a web component using those techniques by bringing back the <blink> tag!

Defining our tag

JavaScript

// blink.js
const Blink = (function() {
  "use strict";

  class Component extends HTMLElement {
    constructor() {
      super();
      // Create shadow root
      const shadow = this.attachShadow({
        mode: "open"
      });

      // Wrap text content with a span tag
      const wrapper = document.createElement("span");

      // Make a slot for text
      const slot = document.createElement("slot");
      slot.setAttribute("name", "content");
      wrapper.appendChild(slot);

      // CSS animation styles
      const style = document.createElement("style");
      style.textContent = `
        @keyframes blink {
          0%   { visibility: hidden; }
          50%  { visibility: hidden; }
          100% { visibility: visible; }
        }
        /* :host selects shadow root host */
        :host { animation: 1s linear infinite blink; }
      `;

      // Append
      shadow.appendChild(wrapper);
      wrapper.appendChild(style);
    }
  }
  customElements.define("wc-blink", Component); // can't use <blink> - it's still reserved
})();

export { Blink };

Putting it to use

HTML

<script>
  import { Blink } from "./blink.js";
</script>

<!-- prettier-ignore -->
<wc-blink>
  <h1 slot="content">
    Look Ma, I'm blinking!
  </h1>
</wc-blink>

I learned a bunch in this session on how the Shadow DOM is used to make custom elements and the benefits & limitations of such. I walked away with an understanding that it is possible to create a component-based site/application without a framework if need be. Though certainly the additional features of a framework may outweigh the freedom of independence, it is good to know there are options.

← Back to main JS&Friends article

Top comments (0)