In my previous article, I explained the basics of creating custom tags. In fact, custom tags eliminate some of the brittleness when building great web applications. However, the pursuit of control does not stop, and traditional custom tags are not enough to build performance-rich applications. For example, the number of style selectors in your code may increase with the addition of custom tags. This is just one of many factors that can cause performance issues.
One way to solve this problem is through Shadow DOM.
Shadow DOM works by introducing scoped styles. It doesn't require any special naming conventions or tools. With Shadow DOM, bundling CSS with markup is easy. Furthermore, this feature allows us to hide all details about the implementation in plain JavaScript.
Shadow DOM provides the following solutions:
document.querySelector
do not return orphaned elements.To demonstrate Shadow DOM, we will use a simple component calledtuts-tabs
. All references in this article will point to this code. To experience Shadow DOM, take a look at the demo below:
Before you start coding with Shadow DOM, you need to understand the regular DOM.
HTML is the backbone of the website. In just a few minutes, you can create a page. When you open the page in your browser, the DOM comes into play. Once the browser loads the page, it starts parsing the HTML into a data model. The data model is a tree structure in which the nodes represent elements in HTML. The data model is easy to modify and manipulate with code.
The disadvantage is that entire web pages and even complex web applications are treated as a single data structure. This is not easy to debug! For example, a CSS style applied to one component may end up affecting another component elsewhere in the application.
You useiframe
s when you want to isolate part of the interface from the rest. But iframes are heavy and extremely restrictive.
This is why Shadow DOM was introduced. It is a powerful feature of modern browsers that allows web developers to include subtrees of various elements in the DOM. These subtrees of the DOM do not affect the main document tree. Technically, they are calledShadow Trees.
A shadow tree has ashadow root, which is attached to a parent in the DOM. This parent is calledShadow Host.
For example, if you pluginto a browser powered by WebKit, it will be converted into a slider. Why? This is a slider because one of the subtree DOM elements understands "scope" to change its appearance and introduce slider-like functionality. This is an advantage that Shadow DOM brings to tabs.
Wow, that’s a lot of theories. Now, you might want to write some code to see how Shadow DOM is implemented.
Useelement.attachShadow()
to create a Shadow DOM element.
In our exampletuts-tab
, you will see the code used to create a Shadow DOM element.
let shadowRoot = this.attachShadow({mode: 'open'});
Next, we will use.innerHTML
to add content to the shadow root. Note that this is not the only way to populate the Shadow DOM. There are many APIs that help you populate the Shadow DOM.
shadowRoot.innerHTML = ``
Connecting custom elements to Shadow DOM is very simple. Keep in mind that when you combine custom elements with Shadow DOM, you'll be able to create encapsulated components using CSS, JavaScript, and HTML. Therefore, you will create a completely new web component that can be reused in your application.
In our example, we create a new custom element usingcustomElements.define()
. As mentioned in the previous tutorial, new elements should contain "-" in their name.tuts-tabs
The component extendsHTMLElement
.
当我们扩展HTMLElement
时,在构造函数中调用super()
非常重要。另外,构造函数是需要创建shadowRoot
的地方。
customElements.define('tuts-tabs', class extends HTMLElement { constructor() { super(); // always call super() first in the constructor. // Attach a shadow root to. const shadowRoot = this.attachShadow({mode: 'open'}); ... });
创建shadowRoot
后,您可以为其创建 CSS 规则。 CSS 规则可以包含在标记中,并且这些样式的范围仅限于
tuts-tab
。
customElements.define('tuts-tabs', class extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({mode: 'open'}); shadowRoot.innerHTML = ` `; } ... });
与tuts-tab
相关的CSS可以写在标签内。请记住,此处声明的所有样式都将作用于
tuts-tab
Web 组件。作用域 CSS是 Shadow DOM 的一项有用功能,它具有以下属性:
如果你想在 Shadow DOM 中选择自定义元素,你可以使用:host
伪类。当:host
伪类用于普通 DOM 结构时,它不会产生任何影响。但在 Shadow DOM 内部,它会产生很大的差异。您将在tuts-tab
组件中找到以下:host
样式。它决定显示和字体样式。这只是一个简单的示例,展示如何将:host
合并到 Shadow DOM 中。
:host
的一个问题是它的特殊性。如果父页面有:host
,它将具有更高的特异性。父样式内的所有样式都会获胜。这是从外部覆盖自定义元素内部样式的一种方法。
:host { display: inline-block; width: 650px; font-family: 'Roboto Slab'; contain: content; }
随着 CSS 变得更简单,Shadow DOM 的整体效率也会提高。
下面定义的所有样式都是影子根的本地样式。
shadowRoot.innerHTML = `
同样,您可以自由地在 Shadow DOM 中引入样式表。当您在 Shadow DOM 内链接样式表时,它们的作用域将位于 Shadow 树内。这是一个简单的例子来帮助您理解这个概念。
shadowRoot.innerHTML = ` ...
接下来,我们可以定义tuts-tab
的 HTML 元素。
在简单的选项卡结构中,应该有可单击的标题和反映所选标题内容的面板。这显然意味着我们的自定义元素应该有一个带有标题的div
和一个用于面板的div
。 HTML 组件将定义如下:
customElements.define('tuts-tabs', class extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({mode: 'open'}); shadowRoot.innerHTML = ` .... // Our HTML elements for tuts-tab......... `; } ... });
在面板的div
中,您会遇到一个有趣的标签,名为
。我们的下一步是了解有关插槽的更多信息。
Slot在 Shadow DOM API 中起着至关重要的作用。插槽充当自定义组件内的占位符。这些组件可以由您自己的标记填充。槽声明分为三种不同类型:
在我们的tuts-tabs
中,我们有一个用于选项卡标题的命名槽,以及另一个用于面板的槽。命名槽会创建您可以通过名称引用的孔。
customElements.define('tuts-tabs', class extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({mode: 'open'}); shadowRoot.innerHTML = ` .... // Our HTML elements for tuts-tab ... `; } ... });
现在,是时候填充插槽了。在之前的教程中,我们了解了定义自定义元素的四种不同方法,并且tuts-tabs
使用其中两种方法来构建选项卡:connectedCallback
和disconnectedCallback
。
在connectedCallback
中,我们将填充步骤 6 中定义的槽。我们的connectedCallback
将定义如下。我们使用querySelector
来识别tabsSlot
和panelsSlot
。当然,这并不是识别 HTML 中插槽的唯一方法。
识别槽后,您需要为其分配节点。在tuts-tab
中,我们使用以下tabsSlot.assignedNodes
来标识选项卡的数量。
connectedCallback() { ... const tabsSlot = this.shadowRoot.querySelector('#tabsSlot'); const panelsSlot = this.shadowRoot.querySelector('#panelsSlot'); this.tabs = tabsSlot.assignedNodes({flatten: true}); this.panels = panelsSlot.assignedNodes({flatten: true}).filter(el => { return el.nodeType === Node.ELEMENT_NODE; }); ... }
此外,connectedCallback
是我们注册所有事件监听器的地方。每当用户单击选项卡标题时,面板的内容都需要更改。可以在connectedCallback
函数中注册用于实现此目的的事件侦听器。
我们不会深入探讨如何实现选项卡及其功能的逻辑。但是,请记住,我们的自定义tuts-tab
组件中实现了以下方法,用于在选项卡之间切换:
onTitleClick
:该方法捕获选项卡标题上的点击事件。它有助于在选项卡面板内切换内容。selectTab
:该函数负责隐藏面板和显示右侧面板。此外,它还负责突出显示所选的选项卡。findFirstSelected
:此方法用于在第一次加载时选择选项卡。selected
:这是一个用于获取所选选项卡的 getter 和 setter。继续,不要忘记定义disconnectedCallback
。这是自定义元素中的生命周期方法。当自定义元素从视图中销毁时,会触发此回调。这是在应用程序中删除操作侦听器和重置控件的最佳位置之一。但是,回调的范围仅限于自定义元素。在我们的例子中,它将是tuts-tab
。
最后一步是在 HTML 中使用tuts-tab
。我们可以很容易地在 HTML 标记中插入tuts-tab
。这是一个简单的例子来演示其用法。
content panel 1 content panel 2 content panel 3
我们开始了!我们已经完成了一个重要教程,在该教程中我们创建并使用了自定义元素。该过程很简单,并且在开发网页时被证明非常有用。我希望您尝试创建自定义元素并与我们分享您的经验。
The above is the detailed content of Enhance HTML with custom tags and Shadow DOM. For more information, please follow other related articles on the PHP Chinese website!