异步插入包含自定义元素的内容

Inserting content containing Custom Elements asynchronously

本文关键字:元素 自定义 插入 包含 异步      更新时间:2023-09-26

已经有了这个问题和这个问题,但尽管这两个问题都会引发相同的错误,但它们的解决方案和原因并不相同。我有一个标签,它在应用程序的整个生命周期中异步加载内容。此内容又包含导致错误的自定义元素。以下是重现此错误的最简单的测试用例(假设Polymer安装了bower,否则导入看起来会略有不同):

base.html

<link rel="import" href="bower_components/polymer/polymer.html">
<link href="asynchronousTag.html" rel="import">
<asynchronous-tag></asynchronous-tag>

asynchronousTag.html

<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="bower_components/core-tooltip/core-tooltip.html">
<polymer-element name="asynchronous-tag">
    <template>
        <div id="text"></div>
    </template>
    <script>
        Polymer({
            ready:function(){
                var that = this;
                setTimeout(function(){
                     that.$.text.innerHTML = 
                                 '<core-tooltip label="testing">tester</core-tooltip>';
                }, 2500);
            }
        });
    </script>
</polymer-element>

触发错误

核心工具提示上的属性是聚合物升级元素之前的数据绑定。这可能会导致不正确的绑定类型。

尽管工作如预期。当<core-tooltip>为无属性时也会发生同样的情况。然而,当使用插入同一节点时,不会发生

var ct = document.createElement("core-tooltip");
ct.innerHTML = "html";
ct.setAttribute("label","text");
that.$.text.appendChild(ct);

然而,遗憾的是,这对我没有太大帮助,因为我的内容是一个完整的HTML字符串。

我之所以担心这一点,是因为有问题的函数的性能低于标准,所以我希望解决导致错误的问题可能会改善这一点(除了我不希望在控制台上显示任何错误之外)。

写完问题后,我在浏览Polymer邮件组时发现了这封邮件。据说

然而,Element.innerHTML没有触发生命周期回调,也没有升级。

换句话说,解决方案是

var div = document.createElement("div");
div.innerHTML = '<core-tooltip>tester</core-tooltip>';
that.$.text.appendChild(div.childNodes[0]);

是的,这毫无意义。。。这就是为什么我要和全世界分享它。