无法在 'Document' 上执行 'createElement':结果不能有子项

Failed to execute 'createElement' on 'Document': The result must not have children

我通过 polyfill 使用自定义元素 v1 已有一段时间了。 Chrome 54(第一个带有本机 v1 实现的版本)在初始化我的元素时开始抛出错误:

DOMException: Failed to execute 'createElement' on 'Document': The result must not have children

违规行很简单:

let el = document.createElement('my-custom-element');

Chrome 的本机实现似乎在执行 polyfill 没有执行的规范要求。根据规范的“Requirements for custom element constructors”部分:

The element must not gain any attributes or children, as this violates the expectations of consumers who use the createElement or createElementNS methods.

我试图创建的元素在其构造函数中为其自身添加了子项。

解决方案是遵循规范的建议:

In general, work should be deferred to connectedCallback as much as possible—especially work involving fetching resources or rendering. However, note that connectedCallback can be called more than once, so any initialization work that is truly one-time will need a guard to prevent it from running twice.

也就是说,在已连接的回调中添加子项并使用标​​志来确保元素仅在第一次连接时初始化。