This is the sixth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Shadow DOM is one of the three Web Compoent standards. HTML Templates, Shadow DOM, and Custom Elements

shadow DOM

HTML, CSS, and JS are all global and can be overwritten if you are not careful. Especially CSS, it takes a lot of effort to solve the problem of naming conflicts at the design level or at the coding specification level, but a little careless (especially CSS) can cause problems. This POINT I think every web developers wrote a certain depth of experience, can only rely on experience a little bit of investigation and solution. Style selectors lose control, and performance suffers. The list goes on and on.

An important attribute of Web Components is encapsulation — the ability to hide tag structure, style, and behavior from the rest of the code on the page, ensuring that different parts don’t get mixed up, making the code cleaner and cleaner.

Shadow DOM is one of the three Web Compoent standards. HTML Templates, Shadow DOM, and Custom Elements. HTML Import used to be part of this, but is now considered deprecated.

Of course, writing a Shadow DOM is not mandatory when creating Web Components, but if you define how the Web Component introduces the Shadow DOM, then the Shadow DOM gives you a gift package. CSS scope, DOM encapsulation, and composition. This has the obvious benefit of giving custom components a degree of flexibility and reuse.

Use Custom Elements to create HTML using the JS API, and shadow DOM provides HTML and CSS for HTML. Together, these two apis give a component its own space, separate from HTML, CSS, and JavaScript.

Shadow DOM is designed as a tool for building component-based applications. As such, it brings solutions to common problems in web development.

  • Isolated DOM(Isolated DOM): A component’s DOM is Isolated. You cannot retrieve nodes in the component’s shadow DOM using document.querySelector()
  • Scoped CSS: CSS within the Shadow DOM is Scoped. The CSS style rules do not affect the external styles, and the external CSS does not affect the elements in the Shadow DOM
  • Composition: Design a declarative, tag-based API for your components
  • CSS Simplifies – with scoped DOM, you won’t have to worry about naming conflicts because you won’t have to define cumbersome ID /class names to avoid collisions
  • Productivity – Putting applications in chunks of the DOM saves time spent avoiding overlays and conflicts

What is a Shadow DOM?

Background on DOM

If HTML is a language, the first language I came into contact with was HTML. The simplicity and ease of use of HTML helped propel the Web. Simply declaring a few tags made it possible to write a page that was both expressive and structured. While HTML, as a text-based language, is designed to be easy for humans to understand, machines need something more, a document object model, or DOM.

Page loading process

When a browser loads a web page, a number of interesting things happen. One of the things you do is convert the author’s HTML into a document object model (DOM), which is not static. The browser parses HTML (static text strings into data models (objects/nodes), that is, it parses the structure of the page. The resulting tree data structure, known as the DOM, preserves the HTML hierarchy. The cool thing about DOM is that it’s dynamic, unlike static HTML. The dynamic is that you can manipulate the DOM with Javascript.

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const header = document.createElement('header');
        const h1 = document.createElement('h1');
        h1.textContent = 'Hello DOM';
        header.appendChild(h1);
        document.body.appendChild(header);
    </script>
</body>
</html>
Copy the code
<body>
  <header>
    <h1>Hello DOM</h1>
  </header>
</body>
Copy the code

DOM, what do you mean by shadow

Shadow DOM is just a normal DOM, but it differs from normal DOM in two ways

  • Create/use different methods

  • The Shadow DOM also interacts differently with the rest of the page

In general, when you create a DOM node, you add a DOM element to it, and you can add a child to it. In the Shadow DOM, we create a scoped DOM tree and add it to an element that has little to do with the parent. The subtree of this scope is called a shadow Tree. The shadow added to the element is shadow Host, which is a DOM element.

  • Shadow host: a regular DOM node to which the Shadow DOM will be attached.
  • Shadow Tree: Indicates the DOM tree inside the Shadow DOM.
  • Shadow boundary: this is where the Shadow DOM ends and where the regular DOM begins.
  • Shadow root: indicates the root node of the Shadow tree.

Note that Shadow DOM is not a new thing. For a long time in the past, browsers used Shadow DOM to encapsulate the internal structure of some elements in Jining. Take a

Create shadow DOM

The created shadow root can be attached to a DOM Element using element.attachShadow (). This method takes a configuration object with a mode property that can be open or closed:

Mode is the read-only property of ShadowRoot and returns the mode in which ShadowRoot was created (“open” or “closed”). When ShadowRoot’s mode is “closed”, ShadowRoot’s internal implementation cannot be accessed and modified by JavaScript — that is, the implementation is not made public. For example,

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style>
        h1 {
            background-color: yellow;
        }
        
    </style>
</head>
<body>
    <div>
        <div id="container"></div>
        <h1>DOM element</h1>
    </div>
    <script>
        (function (){
            var root = container.attachShadow( { mode: "open"})//Inside element
            var h1 = document.createElement( "h1" )
            h1.textContent = "Inside Shadow DOM"
            h1.id = "inside"
            root.appendChild( h1 )

            //Access inside element
            console.log( container.shadowRoot.querySelector( "#inside"))}) ()</script>
</body>
</html>
Copy the code
var root = container.attachShadow( { mode: "open"})Copy the code

This code is a little surprising. For a div given an ID, we can just use the ID to get the element of the div. Calling Container directly to attachShadow returns a shadow root element, which we can then attach to the shadow root node.

var h1 = document.createElement( "h1" )
            h1.textContent = "Inside Shadow DOM"
            h1.id = "inside"
            root.appendChild( h1 )
Copy the code

If you want to attach a Shadow DOM to a Custom element, you can add the following implementation to the Custom Element constructor (currently, this is the most useful use of the Shadow DOM) :