我不知道为什么会这样,但看起来自定义 html 标签无法在页面加载时正确解析它的内容,如果真的有很多这样的元素。
document.registerElement('x-tag',
{
prototype: Object.create(HTMLElement.prototype, {
attachedCallback: { value: function() {
console.log(this.innerHTML, this.childNodes); // wrong innerHTML and childNodes once in n-occurrences
}
}})
}
);
这是 an example
我的假设是存在某种堆栈,有时这个堆栈会溢出 :)
您对如何修复它有任何想法吗? (我已经在研究 React Fiber 的内幕……从那里获取调度)。
最佳答案
这是因为元素在解析时被添加到 DOM 树中。
这里的文档非常大,所以元素不是一次性添加的,而是分几 block 添加的。有时只添加 1 或 2 个元素(在 block 的末尾),然后创建自定义元素并仅附加其确定的子节点的一部分。
要修复它,您可以仅在解析所有文档后定义自定义元素。把 <script>
在<x-tag>s
之后,或使用 onload
事件。
document.onload = function ()
{
document.registerElement('x-tag', { prototype: proto } )
}
否则,如果由于某些原因自定义元素已经定义,请将大量标签放在 <template>
中元素,然后插入其 content
在一次操作中:
<template id=tpl>
<x-tag></x-tag><x-tag></x-tag><x-tag></x-tag><x-tag></x-tag><x-tag></x-tag><x-tag></x-tag><x-tag></x-tag><x-tag></x-tag><x-tag></x-tag>...
</template>
<script>
target.appendChild( document.importNode( tpl.content, true )
</script>
关于javascript - 由于某种原因,页面呈现上的自定义 html 标记跳过 HTML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40378115/