跳到主要内容

Web组件:终极指南

Web components: Characters © iStock / Getty Images Plus; aurielaki
+$(Image credit: Characters © iStock / Getty Images Plus; aurielaki)

+$With web components, developers now have the ability to create their own HTML elements. In this ultimate guide, you'll learn everything you need to know. On this page, we'll cover what exactly web components are, the benefits of using them, and the elements that make them up.

+$Then you'll learn how to build your own components in two short tutorials – on page 2 you'll learn how to building a component with the HTML templates and shadowDOM APIs, and on page 3 you'll got one step further and learn how to build a customised, built-in element.

+$Finally on page 4 you'll find some frameworks and tools to get you started, and examples of existing elements to try to today.

+$While you're here, you might also want to take a look at our guide to the+$top HTML APIs+$, and how to use them.

+$What are web components?

+$Developers love components. They are a great way to define blocks of code that can be dropped in and reused anywhere they are required. Over the years, there have been a few attempts to convey this idea on the web, with varying degrees of success.

+$Mozilla's XML Binding Language and Microsoft's HTML Component specifications date back all the way to Internet Explorer 5 almost 20 years ago. Unfortunately, both attempts proved unwieldy, failed to gain traction in other browsers, and ultimately were removed. While they may not be around today, their concepts formed the basis of the modern approaches in use.

+$JavaScript frameworks such as React, Vue or Angular follow a similar approach. One of the main reasons for their success is the ability to contain common logic in an easily shareable pattern in one form or another.

+$While these frameworks can improve the developer experience, they do so at a cost. Language features such as JSX need to be compiled, and many frameworks rely on a runtime to manage all of their abstractions. Wouldn't it be easier if there was a way to get the benefit without all that heavy weight? Web components allow us to do just that.

Web组件的四大支柱

+$The concept of a web component consists of three APIs – Custom elements, HTML templates and the shadow DOM – with JavaScript modules gluing them together. By combining the benefits that these technologies provide, it's possible to start building custom HTML elements that look and behave just like their native counterparts.

+$Using a web component is much like using any other existing HTML element. They can be configured using attributes, queried for using JavaScript, and even styled through CSS. As long as the browser knows they exist, they are treated no differently.

+$This also allows web components to play well with other frameworks and libraries. By using the same communication mechanisms as any other element, they can be used alongside any framework that exists today or in the future.

+$Most importantly of all, these are all built upon web standards. The web is built on a concept of backwards compatibility, and by building a web component today, it will carry on working for years to come.

+$But before going any further, we should take a look at what makes up these specifications, and how you can get creating and using one today.

web components

+$There are four main elements that make up web components

(图片来源:马特·克劳奇)

+$01. Custom Elements

主要特点:

  • +$Define an element's behaviour
  • +$React to attribute changes
  • +$Augment Existing Elements

+$When you hear people talk about 'web components,' quite often they are referring to the workings underneath – the custom elements API.

+$With this API, it is possible to create classes that power the inner workings of an element. They detail exactly what to do when an element is added, updated or removed.

+$class ExampleElement extends HTMLElement { static get observedAttributes() { return […]; } attributeChangedCallback(name, oldValue, newValue) {} connectedCallback() {} } customElements.define("example-element", ExampleElement);

+$Each custom element has a similar structure. They extend an existingHTMLElement+$class, which provides the groundwork for how an element should behave.

+$Inside, there are a few methods called+$reactions+$that are called in response to something about that element changing. For example,ConnectedCallback+$will be called when the new element appears on screen. These work similarly to the lifecycle methods found in most JavaScript frameworks.

+$Updating the attributes on an element can change how it behaves. When an update happens, theAttributeChangedCallback+$reaction will fire, which details the change. This will only happen for an attribute that is defined inside the observedAttributes array.

+$An element needs to be defined before the browser can do anything with it. The定义+$method here takes two arguments – the tag name, and the class it should use. All tag names must contain a-+$character to avoid any clashes with any future native elements.

+$Content

+$The element can then be written anywhere in the page as a regular HTML tag. Once a browser has an element defined, it then finds any of these matching tags and links up their behaviour to the class in a process known as 'upgrading'.

+$There are two types of custom element – 'autonomous' or 'customised built-in'. Autonomous custom elements, which have been covered up until now, are not related to any existing element. Much like a

要么+$they do not provide any meaning to their content.

+$A customised built-in element – as the name implies – can enhance an existing element with new functionality. They maintain that element's normal semantic behaviours, while also being open to change. If an+$element was customised, for example, it would still be picked up and submitted as part of a form.

+$class CustomInput extends HTMLInputElement {} customElements.define("custom-input", CustomInput, { extends: "input" });

+$The class of customised built-in component extends the class of the element it is customising. The definition also needs to define the tag of that element through its third argument.

+$

+$They are also used slightly differently. Instead of a new tag, they extend the existing tag by using the+$attribute. The browser can read this, and upgrade them in the same way as it can an autonomous component.

+$While most browsers support autonomous custom elements, Only Chrome and Firefox support customised built-in elements. If used in a browser that does not support them, they will fall back to the regular versions of the elements they customise, which can make them safe to use.

+$02. HTML Templates

  • +$Create Ready-made Structures
  • +$Inert until called upon
  • +$Contains HTML, CSS and JS

+$Historically, browser-based templating involved stitching strings together in JavaScript, or using a library like Handlebars to parse a block special markup. More recently, the HTML templates specification defined the