In the previous Web Components series, a brief introduction to the Web Components overview, HTML Templates,shadow Dom,shadow DOM (ii).
Based on this, this article describes how the shadow DOM works with HTML templates.
In Shadow Dom (ii), it describes how to create a shadow dom: Create a root node by calling the Createshadowroot () method, and then create a normal HTML node in JavaScript and attach the nodes to shadow root. But this is cumbersome, because ordinary HTML tags are also created through the JavaScript method. Ordinary HTML nodes, should be created in a declarative way more convenient and reasonable.
and HTML templates gives us the ability to do that. The introduction of HTML templates is visible here.
<! DOCTYPE html>
Root.appendchild (Document.importnode (Tmpl.content, true)); </script></body>
In this sample code, you first create an HTML template from the template tag. The two lines of code in front of JavaScript are the same as in the Shadow DOM (ii), followed by two lines of code, first getting to the template node, and then attaching the template's contents (content) to root.Run in the browser to get the effect as shown:
With this example, you can see how the template is used to create the Shadow DOM, which is easier, and can include information such as styles in the template, which is cumbersome and poorly maintainable if created directly in JavaScript.
Shadow DOM and HTML Templates