我们如何观察 v0 影子根的分布变化?

How do we observe distribution changes on a v0 shadow root?

在 v1 影子根中,我们可以在 <slot> 元素上监听 slotchange,然后使用 slot.assignedNodes() 检测变化。我正在寻找一种方法来使用 v0 影子根。

使用 ShadowDOM v0,有没有办法观察影子根中 <content> 元素的分布式节点的变化?

最简单的实现方法是使用 requestAnimationFrame 创建一个轮询循环,调用 content.getDistributedNodes() 将新结果与旧结果进行比较,但显然轮询并不理想且成本高昂。

如何做到?

我和你差不多同时需要这个东西。我最终为此创建了一个库,我已经在测试中使用了一个星期左右。该库名为 content-change。它对我来说效果很好,但我相信还有很多改进的机会。

它是这样工作的;类似于来自 Shadow DOM v1:

slot 元素的 slotchange 事件
// Because this is non-spec, specify internally which components get to be watched
// "this" is the host element
ContentChange.watch(this);

const contentElement = shadow.querySelector('someContentSelector');
contentElement.addEventListener('contentchange', e => {
    // React to distributed node changes for this content element
});

返回给监听器的eventevent.details中包含几个不同的类型。 event.details.type 将是以下三个之一:

  • "nodesAdded"
  • "nodesRemoved"
  • "mutation"

允许您对不同的场景做出反应。例如,当添加到宿主元素的节点满足分发到该内容元素的要求时,您将收到以下内容:

{
    "type": "nodesAdded",
    "nodesAdded": [Nodes] // An array of newly distributed nodes
}