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

The state of Web Components的更多相关文章

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

    原文转自:http://segmentfault.com/blog/nightire/1190000000753400 译者前言 这是一篇来自 StackOverflow 的问答,提问的人认为 Rea ...

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

    目录结构 译者前言 Native vs. Compiled 原生语言对决预编译语言 Internal vs. External DSLs 内部与外部 DSLs 的对决 Types of DSLs - ...

  3. 前端未来趋势之原生API:Web Components

    声明:未经允许,不得转载. Web Components 现世很久了,所以你可能听说过,甚至学习过,非常了解了.但是没关系,可以再重温一下,温故知新. 浏览器原生能力越来越强. js 曾经的 JQue ...

  4. 【shadow dom入UI】web components思想如何应用于实际项目

    回顾 经过昨天的优化处理([前端优化之拆分CSS]前端三剑客的分分合合),我们在UI一块做了几个关键动作: ① CSS入UI ② CSS作为组件的一个节点而存在,并且会被“格式化”,即选择器带id前缀 ...

  5. Web Components初探

    本文来自 mweb.baidu.com 做最好的无线WEB研发团队 是随着 Web 应用不断丰富,过度分离的设计也会带来可重用性上的问题.于是各家显神通,各种 UI 组件工具库层出不穷,煞有八仙过海之 ...

  6. Web Components之Custom Elements

    什么是Web Component? Web Components 包含了多种不同的技术.你可以把Web Components当做是用一系列的Web技术创建的.可重用的用户界面组件的统称.Web Com ...

  7. 可选的Web Components类库

    首先需要说明的是这不是一篇 Web Components 的科普文章,如果对此了解不多推荐先读<A Guide to Web Components>. 有句古话-“授人以鱼,不如授人以渔” ...

  8. Polymer——Web Components的未来

    什么是polymer? polymer由谷歌的Palm webOS团队打造,并在2013 Google I/O大会上推出,旨在实现Web Components,用最少的代码,解除框架间的限制的UI 框 ...

  9. Web Components

    Web Components是不是Web的未来   今天 ,Web 组件已经从本质上改变了HTML.初次接触时,它看起来像一个全新的技术.Web组件最初的目的是使开发人员拥有扩展浏览器标签的能力,可以 ...

随机推荐

  1. [整理]:oracle spool 用法

    本文来自iDB Stock:http://www.idb-stock.net/idb/2011/06/01/153.html 1.spool的作用是什么? spool的作用可以用一句话来描述:在sql ...

  2. verilog 常用系统函数及例子

    1.打开文件 integer file_id; file_id = fopen("file_path/file_name"); 2.写入文件:$fmonitor,$fwrite,$ ...

  3. ffmpeg之yuv2rgb_c_24_rgb

    YUV2RGBFUNC(yuv2rgb_c_24_rgb, uint8_t, ) LOADCHROMA(); PUTRGB24(dst_1, py_1, ); PUTRGB24(dst_2, py_2 ...

  4. Bye 14 Hello 15

         打开博客.空间 窥探到大家都在写自己的2014,抬头一看日历2015已近在咫尺了,看着别人的成长(例如 今年看了多少书.做了什么项目.工资涨了多少.职位角色的变化.去了多少地方.还有一些发善 ...

  5. Android 70道面试题汇总

    1. 下列哪些语句关于内存回收的说明是正确的? (b) A. 程序员必须创建一个线程来释放内存 B. 内存回收程序负责释放无用内存 C. 内存回收程序允许程序员直接释放内存 D. 内存回收程序可以在指 ...

  6. Ext.Net学习笔记08:Ext.Net中使用数据

    之前的七篇文章都是介绍Ext.Net较为基础的东西,今天的这一篇将介绍数据的一些用法,包括XTemplate绑定数据.Store(Modal.Proxy).ComboBox的用法等. XTemplat ...

  7. Swift 语法须知

    什么是swift? swift是 2014 WWDC 发布的一款脚本语言. 使用Swift的好处: OC ARC    最大的困难  内存管理 而  swift  不用担心内存方面.   简洁 ,功能 ...

  8. Prism for WPF 第一讲 Event机制

    在本篇文章中主要讲解在Prism中模块与模块之间事件关联的机制.在这里牵涉到三个名词:事件定义,事件发布,事件订阅. 第一:事件定义 在公共类库中定义事件. ①没有参数事件 public class ...

  9. 10.20_web编辑器复制粘贴图片

    (1) http://q.cnblogs.com/q/19865/ (2) http://www.oschina.net/search?scope=project&q=FreeTextBox

  10. Cogs 1844. [JSOI2008]最大数maxnumber

    [JSOI2008]最大数maxnumber ★★ 输入文件:bzoj_1012.in 输出文件:bzoj_1012.out 简单对比 时间限制:3 s 内存限制:162 MB [题目描述] 现在请求 ...