현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

Web Components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.

웹컴포넌트는 다른 재사용가능한 커스텀 엘리멘트를 생성하는것을 허용하여 다른 기술들의  묶음이다 — 커스텀엘리멘트는 기능적으로 다른 코드와 분리되어 캡슐화된다  — 웹 어플리케이션에서 커스텀 엘리멘트를 활용 할수있다.

Concepts and usage(개념과 사용)

As developers, we all know that reusing code as much as possible is a good idea. This has traditionally not been so easy for custom markup structures — think of the complex HTML (and associated style and script) you've sometimes had to write to render custom UI controls, and how using them multiple times can turn your page into a mess if you are not careful.

개발자들은 , 가능한 재사용 가능한 코드를 많을수록 좋다고 생각한다. 이것은 전통적으로 커스텀 마크업 구조들에서는 쉽지 않다.  — 복잡한 HTML을 (스타일과 스크립트도 연관된 ) 생각해보자 우리는 가끔 커스텀 UI를 컨트롤 할수있게 해야하고 , 우리가 주의없이, 커스텀 UI를  여러번 사용할때 페이지가 엉망으로 될수 있다.

Web Components aims to solve such problems — it consists of four main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions.

웹 컴포넌트는 그러한 문제들을 해결하는 것이 목표( 커스텀 UI 재사용과 구현의 복잡성 제거)다. — 이것은 주요 4가지 기술로 구성된다, 여러기능을 가진 커스텀 엘리멘트들을 함께 사용할수 있게 해주고 , 커스텀 엘리멘트는 코드의 충돌에 대한 걱정없이 재사용 가능하도록 기능적으로 캡슐화된다. (역자 추가 설명 : 커스텀 엘리멘트는 코드상의 격리가 가능함) 

  • Custom elements: A set of JavaScript APIs that allow you to define custom elements and their behaviour, which can then be used as desired in your user interface.
  • Custom elements:  커스텀 엘리멘트에 의도한 유저 인터페이스로 사용될수 있도록 하여 커스텀 엘리멘트를 정의할수 있도록한 자바스크립트 API이다.   
  • Shadow DOM: A set of JavaScript APIs for attaching an encapsulated "shadow" DOM tree to an element — which is rendered separately from the main document DOM — and controlling associated functionality. In this way you can keep an element's features private, so they can be scripted and styled without the fear of collision with other parts of the document.
  • Shadow DOM: 캡슐화된 "shadow" DOM tree를 엘리멘트에 붙이는 자바스크립트 API이다 — 이것은 메인 document DOM으로부터 분리되어 렌더링된다 —   그리고 연관된 기능들을 제어하도록한다. 이러한 방법은 엘리멘트들의 특징들을 private(개별화) 하고 , 그래서 document의 다른 부분의 충돌에 대한 걱정 없이 스크립팅과 스타일링되게 할수 있다.(별도의 공간으로 격리하여 처리하므로 충돌이 안됨)
  • HTML templates: The <template> and <slot> elements enable you to write markup templates that are not displayed in the rendered page. These can then be reused multiple times as the basis of a custom element's structure.
  • HTML templates: The <template> and <slot> 엘리멘트는  렌더링된 페이지에서 아직 보여지지 않는 마크업 템플릿을 작성할수 있도록 한다. 이것은 커스텀 엘리멘트의 구조의 기본으로써 매번마다 재사용할수 있게 한다.
  • HTML Imports: Once you've defined a custom component, the easiest way to reuse it is to keep its definition details in a separate file and then use an import mechanism to import it into pages where you want to actually use it. HTML Imports is one such mechanism, although there is controversy over it — Mozilla fundamentally disagrees with this approach and is intending to implement something more suitable in the future.
  • HTML Imports: 커스텀 컴포넌트로 정의한다면 , 더 쉬운 방법 재사용 할수있도록 이것을 상세하게 파일로 구분하도록 하고서,  그리고 나면 실제로 이것을 사용하려는 곳에서, 페이지에   import mechanism을 사용하는 것이다. HTML Imports 는 어떤 하나의 메카니즘이다 , 비록 여기에는 논란은 있지만 — Mozilla는 기본적으로 이러한 방식에 동의하지 않지만 미래에 더 어울리는 방식으로 구현하려고 의도하고 있다.

The basic approach for implementing a web component generally looks something like this: 

웹 컴포넌트를 구현하는 기본적인  방식 아래와 같다:

  1. Create a class in which to specify your web component functionality using the ECMAScript 2015 class syntax (see Classes for more information). 웹 컴포넌트의 기능들은  ECMAScript 2015 class 문법을 사용하여 정의하도록 생성하라(Classes 에 대한 상세 정보 보기) 
  2. Register your new custom element using the CustomElementRegistry.define() method, passing it the element name to be defined, class in which its functionality is specified, and optionally, what element it inherits from. CustomElementRegistry.define() method를 사용하여 새로운 커스텀  엘리멘트를  이름을 정의하고 , 기능을 정의한 class 와 선택적으로 , 어떤 것으로부터 상속받을지를 지정하여 전달하여 등록하라.
  3. If required, attach a shadow DOM to the custom element using Element.attachShadow() method. Add child elements, event listeners, etc., to the shadow DOM using regular DOM methods. 만약 필요하다면, Element.attachShadow()  method를 사용하여 커스텀 엘리멘트에  shadow DOM을 붙어라. 자식 엘리멘트, 이벤트 리스너 등을 추가하라. 일반적인 DOM methods를 shadow DOM에 사용하기 위해서. 
  4. If required, define an HTML template using <template> and <slot>. Again use regular DOM methods to clone the template and attach it to your shadow DOM. 만약 필요하다면 , <template> and <slot>를 사용하여 HTML template를 정의한다. 템플릿을 복제하기 위해서 다시 일반적인DOM  methods 사용하고 , shadow DOM에 이것을 다시 붙어라.
  5. Use your custom element wherever you like on your page, just like you would any regular HTML element. 페이지에서 어디든지 커스텀 엘리멘트를 사용하라 , 단지 일반적인 HTML 엘리멘트 처럼하라.

Tutorials

Using custom elements (커스텀 엘리멘트 사용하기)    
A guide showing how to use the features of custom elements to create simple web components, as well as looking into life cycle callbacks and some other more advanced features.
Using shadow DOM(shadowDOM 사용하기)
A guide that looks at shadow DOM fundamentals, showing how to attach a shadow DOM to an element, add to the shadow DOM tree, style it, and more.
Using templates and slots(templates and slots 사용하기)
A guide showing how to define a reusable HTML structure using <template> and <slot> elements, and then use that structure inside your web components.

Reference

Custom elements

CustomElementRegistry
Contains functionality related to custom elements, most notably the CustomElementRegistry.define() method used to register new custom elements so they can then be used in your document.
Window.customElements
Returns a reference to the CustomElementRegistry object.
Life cycle callbacks
Special callback functions defined inside the custom element's class definition, which affect its behavior:
  • connectedCallback: Invoked when the custom element is first connected to the document's DOM.
  • disconnectedCallback: Invoked when the custom element is disconnected from the document's DOM.
  • adoptedCallback: Invoked when the custom element is moved to a new document.
  • attributeChangedCallback: Invoked when one of the custom element's attributes is added, removed, or changed.
Extensions for creating custom built-in elements
  • The is global HTML attribute: Allows you to specify that a standard HTML element should behave like a registered custom built-in element.
  • The "is" option of the Document.createElement() method: Allows you to create an instance of a standard HTML element that behaves like a given registered custom built-in element.
CSS pseudo-classes
Pseudo-classes relating specifically to custom elements:
  • :defined: Matches any element that is defined, including built in elements and custom elements defined with CustomElementRegistry.define()).
  • :host: Selects the shadow host of the shadow DOM containing the CSS it is used inside.
  • :host(): Selects the shadow host of the shadow DOM containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host.
  • :host-context(): Selects the shadow host of the shadow DOM containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host's ancestor(s) in the place it sits inside the DOM hierarchy.

Shadow DOM

ShadowRoot
Represents the root node of a shadow DOM subtree.
DocumentOrShadowRoot
A mixin defining features that are available across document and shadow roots.
Element extensions
Extensions to the Element interface related to shadow DOM:
  • The Element.attachShadow() method attaches a shadow DOM tree to the specified element.
  • The Element.shadowRoot property returns the shadow root attached to the specified element, or null if there is no shadow root attached.
Relevant Node additions
Additions to the Node interface relevant to shadow DOM:
  • The Node.getRootNode() method returns the context object's root, which optionally includes the shadow root if it is available.
  • The Node.isConnected property returns a boolean indicating whether or not the Node is connected (directly or indirectly) to the context object, e.g. the Document object in the case of the normal DOM, or the ShadowRoot in the case of a shadow DOM.
Event extensions
Extensions to the Event interface related to shadow DOM:
  • Event.composed: Returns a Boolean which indicates whether the event will propagate across the shadow DOM boundary into the standard DOM (true), or not  (false).
  • Event.composedPath: Returns the event’s path (objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with ShadowRoot.mode closed.

HTML templates

<template>
Contains an HTML fragment that is not rendered when a containing document is initially loaded, but can be displayed at runtime using JavaScript, mainly used as the basis of custom element structures. The associated DOM interface is HTMLTemplateElement.
<slot>
A placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together. The associated DOM interface is HTMLSlotElement.
The slot global HTML attribute
Assigns a slot in a shadow DOM shadow tree to an element.
Slotable
A mixin implemented by both Element and Text nodes, defining features that allow them to become the contents of an <slot> element. The mixin defines one attribute, Slotable.assignedSlot, which returns a reference to the slot the node is inserted in.
Element extensions
Extensions to the Element interface related to slots:
  • Element.slot: Returns the name of the shadow DOM slot attached to the element.
CSS pseudo-elements
Pseudo-elements relating specifically to slots:
  • ::slotted: Matches any content that is inserted into a slot.
The slotchange event
Fired on an HTMLSlotElement instance (<slot> element) when the node(s) contained in that slot change.

Examples

We are building up a number of examples in our web-components-examples GitHub repo. More will be added as time goes on.

Specifications

Specification Status Comment
HTML Living Standard
The definition of 'template element' in that specification.
Living Standard  
HTML Living Standard
The definition of 'custom elements' in that specification.
Living Standard  
DOM
The definition of 'shadow trees' in that specification.
Living Standard  
Shadow DOM Working Draft  
HTML Imports Working Draft  
CSS Scoping Module Level 1 Working Draft  

Browser support

In general, web components are supported well in Chrome and Opera — most features have been enabled by default for a while. Firefox has experimental support for most features, disabled by default, which looks to be enabled by default by about version 63. Safari supports a number of features, but less than the above browsers, and Edge is working on an implementation.

For browser support of specific features, you'll have to consult the reference pages listed above.

Notes

  • To enable custom elements and shadow DOM in Firefox, set the dom.webcomponents.customelements.enabled and dom.webcomponents.shadowdom.enabled preferences to true.

See also

  • webcomponents.org — site featuring web components examples, tutorials, and other information.
  • Polymer — Google's web components framework — a set of polyfills, enhancements, and examples. Currently the easiest way to use web components cross-browser.

문서 태그 및 공헌자

이 페이지의 공헌자: ByeongGi, namkwon, maybe
최종 변경: ByeongGi,