【问题标题】:Custom html tags on page render skip HTML parsing for some reason页面渲染上的自定义 html 标签由于某种原因跳过了 HTML 解析
【发布时间】:2016-11-02 10:51:10
【问题描述】:

我不知道为什么会这样,但是如果真的有很多这样的元素,自定义 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 的引擎盖下寻找 .. 从那里获得调度)。

【问题讨论】:

  • @Supersharp 看起来像是与 chrome 相关的问题。顺便说一句,你用什么浏览器?
  • 也在 Opera 上,但它是相同的 引擎:-/

标签: javascript html web-component custom-element html5-template


【解决方案1】:

这是因为元素在解析时被添加到 DOM 树中。

这里的文档非常大,所以元素不是一次性添加的,而是分几块添加的。有时只添加 1 或 2 个元素(在块的末尾),然后创建自定义元素并将其附加到其确定的子节点中。

要修复它,您只能在解析完所有文档后定义自定义元素。将<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>

【讨论】:

  • “元素不是在一次传递中添加的,而是在几个块中添加的”看起来就是这个问题,但由于某种原因只出现在 chrome 中(ff,safari 没有这样的问题)。你的答案的第二部分是什么意思?将 的内部 html 更改为:
  • FF 和 Safari 不实现自定义元素。如果你使用 polyfill,我认为它会等待 onload 事件。我更新了我的答案。
  • 哦,看起来像
猜你喜欢
  • 2013-12-25
  • 1970-01-01
  • 1970-01-01
  • 2018-10-16
  • 2018-10-08
  • 2017-04-19
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多