Enhance HTML with custom tags and Shadow DOM

WBOY
Release: 2023-08-29 09:37:07
Original
940 people have browsed it

使用自定义标签和 Shadow DOM 增强 HTML

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.

Why use Shadow DOM?

Shadow DOM provides the following solutions:

  • Allow independent elements in the DOM. Queries such asdocument.querySelectordo not return orphaned elements.
  • Allow scoped CSS. Scoped CSS ensures that all style rules remain within the page. It also means simpler CSS selectors without any naming conflicts and many common classes.

Our example

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:

Understanding Shadow DOM

What is Shadow DOM?

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 useiframes 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.

Step-by-step guide to using Shadow DOM

Step 1: Create Shadow DOM Element

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'});
Copy after login

Step 2. Add content to Shadow Root

Next, we will use.innerHTMLto 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 = ``
Copy after login

Step 3: Connect custom elements to Shadow DOM

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-tabsThe 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'}); ... });
Copy after login

创建shadowRoot后,您可以为其创建 CSS 规则。 CSS 规则可以包含在 `; } ... });

Copy after login

第 4 步:向 Shadow DOM 添加样式

tuts-tab相关的CSS可以写在

Copy after login

同样,您可以自由地在 Shadow DOM 中引入样式表。当您在 Shadow DOM 内链接样式表时,它们的作用域将位于 Shadow 树内。这是一个简单的例子来帮助您理解这个概念。

shadowRoot.innerHTML = `   ...
Copy after login

步骤 5. 在自定义组件中定义 HTML 元素

接下来,我们可以定义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 
...
...
... `; } ... });
Copy after login

在面板的div中,您会遇到一个有趣的标签,名为。我们的下一步是了解有关插槽的更多信息。

第 6 步:在 Shadow DOM 中使用槽

Slot在 Shadow DOM API 中起着至关重要的作用。插槽充当自定义组件内的占位符。这些组件可以由您自己的标记填充。槽声明分为三种不同类型:

  1. 您可以拥有零个插槽的组件。
  2. 您可以创建一个包含后备内容或空内容的槽位。
  3. 您可以使用整个 DOM 树创建槽。

在我们的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 
... `; } ... });
Copy after login

第 7 步:填充插槽

现在,是时候填充插槽了。在之前的教程中,我们了解了定义自定义元素的四种不同方法,并且tuts-tabs使用其中两种方法来构建选项卡:connectedCallbackdisconnectedCallback

connectedCallback中,我们将填充步骤 6 中定义的槽。我们的connectedCallback将定义如下。我们使用querySelector来识别tabsSlotpanelsSlot。当然,这并不是识别 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; }); ... }
Copy after login

此外,connectedCallback是我们注册所有事件监听器的地方。每当用户单击选项卡标题时,面板的内容都需要更改。可以在connectedCallback函数中注册用于实现此目的的事件侦听器。

第 8 步:实现逻辑和交互性

我们不会深入探讨如何实现选项卡及其功能的逻辑。但是,请记住,我们的自定义tuts-tab组件中实现了以下方法,用于在选项卡之间切换:

  1. onTitleClick该方法捕获选项卡标题上的点击事件。它有助于在选项卡面板内切换内容。
  2. selectTab该函数负责隐藏面板和显示右侧面板。此外,它还负责突出显示所选的选项卡。
  3. findFirstSelected此方法用于在第一次加载时选择选项卡。
  4. selected这是一个用于获取所选选项卡的 getter 和 setter。

第 9 步.定义生命周期方法

继续,不要忘记定义disconnectedCallback。这是自定义元素中的生命周期方法。当自定义元素从视图中销毁时,会触发此回调。这是在应用程序中删除操作侦听器和重置控件的最佳位置之一。但是,回调的范围仅限于自定义元素。在我们的例子中,它将是tuts-tab

第 10 步。使用新组件!

最后一步是在 HTML 中使用tuts-tab。我们可以很容易地在 HTML 标记中插入tuts-tab。这是一个简单的例子来演示其用法。

    
content panel 1
content panel 2
content panel 3
Copy after login

结论

我们开始了!我们已经完成了一个重要教程,在该教程中我们创建并使用了自定义元素。该过程很简单,并且在开发网页时被证明非常有用。我希望您尝试创建自定义元素并与我们分享您的经验。

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!