The state of Web Components

Web Components have been on developers’ radars for quite some time now. They were first introduced by Alex Russell atFronteers Conference 2011. The concept shook the community up and became the topic of many future talks and discussions.

In 2013 a Web Components-based framework called Polymer was released by Google to kick the tires of these new APIs, get community feedback and add some sugar and opinion.

By now, 4 years on, Web Components should be everywhere, but in realityChrome is the only browser with ‘some version’ of Web Components. Even with polyfills it’s clear Web Components won’t be fully embraced by the community until the majority of browsers are on-board.

Why has this taken so long?

To cut a long story short, vendors couldn’t agree.

Web Components were a Google effort and little negotiation was made with other browsers before shipping. Like most negotiations in life, parties that don’t feel involved lack enthusiasm and tend not to agree.

Web Components were an ambitious proposal. Initial APIs were high-level and complex to implement (albeit for good reasons), which only added to contention and disagreement between vendors.

Google pushed forward, they sought feedback, gained community buy-in; but in hindsight, before other vendors shipped, usability was blocked.

Polyfills meant theoretically Web Components could work on browsers that hadn’t yet implemented, but these have never been accepted as ‘suitable for production’.

Aside from all this, Microsoft haven’t been in a position to add many new DOM APIs due to the Edge work (nearing completion). And Apple, have been focusing on alternative features for Safari.

Custom Elements

Of all the Web Components technologies, Custom Elements have been the least contentious. There is general agreement on the value of being able to define how a piece of UI looks and behaves and being able to distribute that piece cross-browser and cross-framework.

‘Upgrade’

The term ‘upgrade’ refers to when an element transforms from a plain oldHTMLElement into a shiny custom element with its defined life-cycle andprototype. Today, when elements are upgraded, their createdCallback is called.

var proto = Object.create(HTMLElement.prototype);
proto.createdCallback = function() { ... };
document.registerElement(‘x-foo‘, { prototype: proto });

There are five proposals so far from multiple vendors; two stand out as holding the most promise.

‘DMITRY’

An evolved version of the createdCallback pattern that works well with ES6 classes. The createdCallback concept lives on, but sub-classing is more conventional.

class MyEl extends HTMLElement {
  createdCallback() { ... }
}

document.registerElement("my-el", MyEl);

Like in today’s implementation, the custom element begins life asHTMLUnknownElement then some time later the prototype is swapped (or ‘swizzled’) with the registered prototype and the createdCallback is called.

The downside of this approach is that it’s different from how the platform itself behaves. Elements are ‘unknown’ at first, then transform into their final form at some point in the future, which can lead to developer confusion.

SYNCHRONOUS CONSTRUCTOR

The constructor registered by the developer is invoked by the parser at the point the custom element is created and inserted into the tree.

class MyEl extends HTMLElement {
  constructor() { ... }
}

document.registerElement("my-el", MyEl);

Although this seems sensible, it means that any custom elements in the initial downloaded document will fail to upgrade if the scripts that contain their registerElement definition are loaded asynchronously. This is not helpful heading into a world of asynchronous ES6 modules.

Additionally synchronous constructors come with platform issues related to .cloneNode().

A direction is expected to be decided by vendors at a face-to-face meeting in July 2015.

is=””

The is attribute gives developers the ability to layer the behaviour of a custom element on top of a standard built-in element.

<input type="text" is="my-text-input">

ARGUMENTS FOR

  1. Allows extending the built-in features of a element that aren’t exposed as primitives (eg. accessibility characteristics, <form> controls,<template>).
  2. They give means to ‘progressively enhance’ an element, so that it remains functional without JavaScript.

ARGUMENTS AGAINST

  1. Syntax is confusing.
  2. It side-steps the underlying problem that we’re missing many key accessibility primitives in the platform.
  3. It side-steps the underlying problem that we don’t have a way to properly extend built-in elements.
  4. Use-cases are limited; as soon as developers introduce Shadow DOM, they lose all built-in accessibility features.

CONSENSUS

It is generally agreed that is is a ‘wart’ on the Custom Elements spec.Google has already implemented is and sees it as a stop-gap until lower-level primitives are exposed. Right now Mozilla and Apple would rather ship a Custom Elements V1 sooner and address this problem properly in a V2 without polluting the platform with ‘warts’.

HTML as Custom Elements is a project by Domenic Denicola that attempts to rebuild built-in HTML elements with custom elements in an attempt to uncover DOM primitives the platform is missing.

Shadow DOM

Shadow DOM yielded the most contention by far between vendors. So much so that features had to be split into a ‘V1′ and ‘V2′ agenda to help reach agreement quicker.

Distribution

Distribution is the phase whereby children of a shadow host get visually ‘projected’ into slots inside the host’s Shadow DOM. This is the feature that enables your component to make use of content the user nests inside it.

CURRENT API

The current API is fully declarative. Within the Shadow DOM you can use special <content> elements to define where you want the host’s children to be visually inserted.

<content select="header"></content>

Both Apple and Microsoft pushed back on this approach due to concerns around complexity and performance.

A NEW IMPERATIVE API

Even at the face-to-face meeting, agreement couldn’t be made on a declarative API, so all vendors agreed to pursue an imperative solution.

All four vendors (MicrosoftGoogleApple and Mozilla) were tasked with specifying this new API before a July 2015 deadline. So far there have been three suggestions. The simplest of the three looks something like:

var shadow = host.createShadowRoot({
  distribute: function(nodes) {
    var slot = shadow.querySelector(‘content‘);
    for (var i = 0; i < nodes.length; i++) {
      slot.add(nodes[i]);
    }
  }
});

shadow.innerHTML = ‘<content></content>‘;

// Call initially ...
shadow.distribute();

// then hook up to MutationObserver

The main obstacle is: timing. If the children of the host node change and we redistribute when the MutationObserver callback fires, asking for a layout property will return an incorrect result.

myHost.appendChild(someElement);
someElement.offsetTop; //=> old value

// distribute on mutation observer callback (async)

someElement.offsetTop; //=> new value

Calling offsetTop will perform a synchronous layout before distribution!

This might not seems like the end of the world, but scripts and browser internals often depend on the value of offsetTop being correct to perform many different operations, such as: scrolling elements into view.

If these problems can’t be solved we may see a retreat back to discussions over a declarative API. This will either be in the form of the current<content select> style, or the newly proposed ‘named slots’ API (fromApple).

A NEW DECLARATIVE API – ‘NAMED SLOTS’

The ‘named slots’ proposal is a simpler variation of the current ‘content select’ API, whereby the component user must explicitly label their content with the slot they wish it to be distributed to.

Shadow Root of <x-page>:

<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
<div>some shadow content</div>

Usage of <x-page>:

<x-page>
  <header slot="header">header</header>
  <footer slot="footer">footer</footer>
  <h1>my page title</h1>
  <p>my page content<p>
</x-page>

Composed/rendered tree (what the user sees):

<x-page>
  <header slot="header">header</header>
  <h1>my page title</h1>
  <p>my page content<p>
  <footer slot="footer">footer</footer>
  <div>some shadow content</div>
</x-page>

The browser has looked at the direct children of the shadow host (myXPage.children) and seen if any of them have a slot attribute that matches the name of a <slot> element in the host’s shadowRoot.

When a match is found, the node is visually ‘distributed’ in place of the corresponding <slot> element. Any children left undistributed at the end of this matching process are distributed to a default (unamed) <slot> element (if one exists).

For:
  1. Distribution is more explicit, easier to understand, less ‘magic’.
  2. Distribution is simpler for the engine to compute.
Against:
  1. Doesn’t explain how built-in elements, like <select>, work.
  2. Decorating content with slot attributes is more work for the user.
  3. Less expressive.

‘closed’ vs. ‘open’

When a shadowRoot is ‘closed’ the it cannot be accessed viamyHost.shadowRoot. This gives a component author some assurance that users won’t poke into implementation details, similar to how you can use closures to keep things private.

Apple felt strongly that this was an important feature that they would block on. They argued that implementation details should never be exposed to the outside world and that ‘closed’ mode would be a required feature when ‘isolated’ custom elements became a thing.

Google on the other hand felt that ‘closed’ shadow roots would prevent some accessibility and component tooling use-cases. They argued that it’s impossible to accidentally stumble into a shadowRoot and that if people want to they likely have a good reason. JS/DOM is open, let’s keep it that way.

At the April meeting it became clear that to move forward, ‘mode’ needed to be a feature, but vendors were struggling to reach agreement on whether this should default to ‘open’ or ‘closed’. As a result, all agreed that for V1 ‘mode’ would be a required parameter, and thus wouldn’t need a specified default.

element.createShadowRoot({ mode: ‘open‘ });
element.createShadowRoot({ mode: ‘closed‘ });

Shadow piercing combinators

A ‘piercing combinator’ is a special CSS ‘combinator’ that can target elements inside a shadow root from the outside world. An example is /deep/ later renamed to >>>:

.foo >>> div { color: red }

When Web Components were first specified it was thought that these were required, but after looking at how they were being used it seemed to only bring problems, making it too easy to break the style boundaries that make Web Components so appealing.

PERFORMANCE

Style calculation can be incredibly fast inside a tightly scoped Shadow DOM if the engine doesn’t have to take into consideration any outside selectors or state. The very presence of piercing combinators forbids these kind of optimisations.

ALTERNATIVES

Dropping shadow piercing combinators doesn’t mean that users will never be able to customize the appearance of a component from the outside.

CSS custom-properties (variables)

In Firefox OS we’re using CSS Custom Properties to expose specific style properties that can be defined (or overridden) from the outside.

External (user):

x-foo { --x-foo-border-radius: 10px; }

Internal (author):

.internal-part { border-radius: var(--x-foo-border-radius, 0); }
Custom pseudo-elements

We have also seen interest expressed from several vendors in reintroducing the ability to define custom pseudo selectors that would expose given internal parts to be styled (similar to how we style parts of <input type=”range”> today).

x-foo::my-internal-part { ... }

This will likely be considered for a Shadow DOM V2 specification.

Mixins – @extend

There is proposed specification to bring SASS’s @extend behaviour to CSS. This would be a useful tool for component authors to allow users to provide a ‘bag’ of properties to apply to a specific internal part.

External (user):

.x-foo-part {
  background-color: red;
  border-radius: 4px;
}

Internal (author):

.internal-part {
  @extend .x-foo-part;
}

Multiple shadow roots

Why would I want more than one shadow root on the same element?, I hear you ask. The answer is: inheritance.

Let’s imagine I’m writing an <x-dialog> component. Within this component I write all the markup, styling, and interactions to give me an opening and closing dialog window.

<x-dialog>
  <h1>My title</h1>
  <p>Some details</p>
  <button>Cancel</button>
  <button>OK</button>
</x-dialog>

The shadow root pulls any user provided content into div.inner via the<content> insertion point.

<div class="outer">
  <div class="inner">
  <content></content>
  </div>
</div>

I also want to create <x-dialog-alert> that looks and behaves just like <x-dialog> but with a more restricted API, a bit like alert(‘foo‘).

<x-dialog-alert>foo</x-dialog-alert>
var proto = Object.create(XDialog.prototype);

proto.createdCallback = function() {
  XDialog.prototype.createdCallback.call(this);
  this.createShadowRoot();
  this.shadowRoot.innerHTML = templateString;
};

document.registerElement(‘x-dialog-alert‘, { prototype: proto });

The new component will have its own shadow root, but it’s designed to work on top of the parent class’s shadow root. The <shadow> represents the ‘older’ shadow root and allows us to project content inside it.

<shadow>
  <h1>Alert</h1>
  <content></content>
  <button>OK</button>
</shadow>

Once you get your head round multiple shadow roots, they become a powerful concept. The downside is they bring a lot of complexity and introduce a lot of edge cases.

INHERITANCE WITHOUT MULTIPLE SHADOWS

Inheritance is still possible without multiple shadow roots, but it involves manually mutating the super class’s shadow root.


var proto = Object.create(XDialog.prototype);

proto.createdCallback = function() {
  XDialog.prototype.createdCallback.call(this);
  var inner = this.shadowRoot.querySelector(‘.inner‘);

  var h1 = document.createElement(‘h1‘);
  h1.textContent = ‘Alert‘;
  inner.insertBefore(h1, inner.children[0]);

  var button = document.createElement(‘button‘);
  button.textContent = ‘OK‘;
  inner.appendChild(button);

  ...
};

document.registerElement(‘x-dialog-alert‘, { prototype: proto });

The downsides of this approach are:

  1. Not as elegant.
  2. Your sub-component is dependent on the implementation details of the super-component.
  3. This wouldn’t be possible if the super component’s shadow root was ‘closed’, as this.shadowRoot would be undefined.

HTML Imports

HTML Imports provide a way to import all assets defined in one .htmldocument, into the scope of another.

<link rel="import" href="/path/to/imports/stuff.html">

As previously stated, Mozilla is not currently intending to implementing HTML Imports. This is in part because we’d like to see how ES6 modules pan out before shipping another way of importing external assets, and partly because we don’t feel they enable much that isn’t already possible.

We’ve been working with Web Components in Firefox OS for over a year and have found using existing module syntax (AMD or Common JS) to resolve a dependency tree, registering elements, loaded using a normal<script> tag seems to be enough to get stuff done.

HTML Imports do lend themselves well to a simpler/more declarative workflow, such as the older <element> and Polymer’s current registration syntax.

With this simplicity has come criticism from the community that Imports don’t offer enough control to be taken seriously as a dependency management solution.

Before the decision was made a few months ago, Mozilla had a working implementation behind a flag, but struggled through an incomplete specification.

What will happen to them?

Apple’s Isolated Custom Elements proposal makes use of an HTML Imports style approach to provide custom elements with their own document scope;: Perhaps there’s a future there.

At Mozilla we want to explore how importing custom element definitions can align with upcoming ES6 module APIs. We’d be prepared to implement if/when they appear to enable developers to do stuff they can’t already do.

To conclude

Web Components are a prime example of how difficult it is to get large features into the browser today. Every API added lives indefinitely and remains as an obstacle to the next.

Comparable to picking apart a huge knotted ball of string, adding a bit more, then tangling it back up again. This knot, our platform, grows ever larger and more complex.

Web Components have been in planning for over three years, but we’re optimistic the end is near. All major vendors are on board, enthusiastic, and investing significant time to help resolve the remaining issues.

Let’s get ready to componentize the web!

MORE

时间: 2024-08-25 15:17:50

The state of Web Components的相关文章

Facebook React 和 Web Components(Polymer)对比优势和劣势

目录结构 译者前言 Native vs. Compiled 原生语言对决预编译语言 Internal vs. External DSLs 内部与外部 DSLs 的对决 Types of DSLs - explanation DSLs 的种类 - 解释 Data binding 数据绑定 Native vs. VM 原生对决 VM(虚拟机) 译者前言 这是一篇来自 StackOverflow 的问答,提问的人认为 React 相比 WebComponents 有一些"先天不足"之处,列举

【转】Facebook React 和 Web Components(Polymer)对比优势和劣势

原文转自:http://segmentfault.com/blog/nightire/1190000000753400 译者前言 这是一篇来自 StackOverflow 的问答,提问的人认为 React 相比 WebComponents有一些“先天不足”之处,列举如下: 原生浏览器支持 原生语法支持(意即不把样式和结构混杂在 JS 中) 使用 Shadow DOM 封装样式 数据的双向绑定 这些都是确然的.不过他还是希望听听大家的看法,于是就有了这篇精彩的回答. 需要说明的是,这篇回答并没有讨

web components折腾记

了解web组件化开发是最初是从了解reactjs开始,但是一直对框架有抵触情绪,另外喜欢不走寻常路,喜欢简单好用的东西,越简单越好,进而开始研究web components.web components这个技术因为太新,浏览器的支持还不完善,还没流行,也没啥中文资料参考,就是官方英文网站貌似都没看到有文档说明,折腾起来甚是费劲.最开始对web components技术还很懵懂,只知道它由几个子技术组成,包括Custom Elements和Shadow DOM还有HTML Imports等等,于是

Web Components之Custom Elements

什么是Web Component? Web Components 包含了多种不同的技术.你可以把Web Components当做是用一系列的Web技术创建的.可重用的用户界面组件的统称.Web Components使开发人员拥有扩展浏览器标签的能力,可以自由的进行定制组件.但截至本文时间,Web Components依然是W3C工作组的一个草案,并为被正式纳入标准,但这并不妨碍我们去学习它. Web组件 何为Web组件?Web组件相对于Web开发者来说并不陌生,Web组件是一套封装好的HTML,

【翻译】为什么web components 如此重要

原文链接:https://blog.revillweb.com/why-web-components-are-so-important-66ad0bd4807a#.gq0m0tt0q 这几年,关于 web components 的争论一直不绝于耳.有人说 web components 可以改变我们构建网页的方式,这是为什么呢,是什么让 web components 如此重要? web component 是一种创建封装的.可复用的网页UI (user interface) 组件的标准化方式. 不

WEBAPP组件化时代, Web Components

polymer   ==> http://docs.polymerchina.org/ angular   ==> http://www.ngnice.com/docs/guide scrat    ==> http://scrat-team.github.io/#!/index component ==> http://component.io/ 前端组件化以及要到来了. 组件化不是新概念,也不是新技术,近年来的环境成熟 推动了 组件化的进步. 前端经常有重复UI界面场景,所以组

Web Components初探

本文来自 mweb.baidu.com 做最好的无线WEB研发团队 是随着 Web 应用不断丰富,过度分离的设计也会带来可重用性上的问题.于是各家显神通,各种 UI 组件工具库层出不穷,煞有八仙过海之势.于是 W3C 坐不住了,大手一挥,说道:不如让我们统一一个 Web Components 的标准吧怎么样. Web Components 的核心思想就是把 UI 元素组件化,即将 HTML.CSS.JS 封装起来,使用的时候就不需要这里贴一段 HTML,那里贴一段样式,最后再贴一段 JS 了.一

Web Components

Web-Components Web Components - 面向未来的组件标准

一个使用 Web Components 的音乐播放器: MelodyPlayer

先上效果预览: Web Components 首先,什么是 Web Components ? MDN 给出的定义是: Web Components 是一套不同的技术,允许您创建可重用的定制元素(它们的功能封装在您的代码之外)并且在您的web应用中使用它们. ... ... 实现web component的基本方法通常如下所示: 使用 ECMAScript 2015 类语法创建一个类,来指定web组件的功能(参阅类获取更多信息). 使用 CustomElementRegistry.define()