嵌套的 Web 组件的 `attachedCallback` 不是 运行 on appended

Nested web component's `attachedCallback` not running on appended

我正在玩 W3C 网络组件。

我有一个主页,其中包含组件 A:

<!-- homepage.html -->
<link rel='import' href='a.html'>
<component-a></component-a>

在组件 A 中,我包含另一个组件 B:

<!-- a.html -->
<link rel='import' href='b.html'>
<template>
  <component-b></component-b>
  <component-b></component-b>
</template>
<script>
  void function() {
    var currentDocument = document.currentScript.ownerDocument
    function getTemplate(selector) {
      return currentDocument.querySelector(selector).content.cloneNode(true)
    }

    var proto = Object.create(HTMLElement.prototype)
    proto.attachedCallback = function() {
      console.log('a')
      this.appendChild(getTemplate('template'))
    }
    document.registerElement('component-a', { prototype: proto })
  }()
</script>

B 的代码与 A 非常相似:

<!-- b.html -->
<template>
  <span>b</span>
</template>
<script>
  void function() {
    var currentDocument = document.currentScript.ownerDocument
    function getTemplate(selector) {
      return currentDocument.querySelector(selector).content.cloneNode(true)
    }

    var proto = Object.create(HTMLElement.prototype)
    proto.attachedCallback = function() {
      console.log('b')
      this.appendChild(getTemplate('template'))
    }
    document.registerElement('component-b', { prototype: proto })
  }()
</script>

奇怪的是,当页面加载时,我只能在控制台中看到 "a"。我也期待 "b" 两次。组件 B 并没有真正被解析。

更奇怪的是,如果我 运行 在控制台中执行以下代码:

document.querySelector('component-a').innerHTML += ''

突然给了我两次"b"

截图如下:

朋友给我一个解决办法,用document.importNode代替cloneNode

function getTemplate(selector) {
  // return currentDocument.querySelector(selector).content.cloneNode(true)
  return document.importNode(currentDocument.querySelector(selector).content, true)
}

而且效果很好。