javascript - 当你的模板有空格/文本节点时,WebKit 会导致 DOM 插入变慢吗?

标签 javascript html templates dom webkit

以下代码在以下浏览器中运行缓慢:

  • Chrome 26.0.1410.65(苹果机)
  • Safari 6.0.4(苹果机)

HTML:

<ul></ul>

<script type="text/html" id="template">
<li>
  Lorem ipsum dolor…
</li>
</script>

CoffeeScript :

# Setup
list = $ 'ul'
templateText = $('#template').text()

# Append 1000 list items
list.append templateText for i in [1..1000]

…但是如果我从模板中删除空格和换行符,它的运行速度会非常快。

自己尝试一下:http://jsfiddle.net/cEK2x/2/

Firefox 26.0 (Mac)、Chrome Canary 28.0.1500.3 (Mac) 和 IE9 不会出现此问题。

最佳答案

丹羽凉介来自WebKit mailing list向我指出the bug filed in the WebKit tracker :

The reason is that we do not create renderers for empty text nodes and thus we are hitting the worst O(N2) case in Node::attach(). (See FIXME in Node::attach().)

This patch adds a logic to bail out the loop to avoid the O(N2) case. Specifically, the patch bails out the loop if we encounter a text node for which we again decided not to create a renderer. This bail out is reasonable because the fact that we again decided not to create a renderer for the text node indicates that there will be no affect of the result of Text::textRendererIsNeeded() of the rest of the sibling nodes.

关于javascript - 当你的模板有空格/文本节点时,WebKit 会导致 DOM 插入变慢吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16428987/

相关文章:

javascript - js 验证(来自 html 输入)问题

javascript - 模板无法使用 Backbone.js 加载

javascript - 如何在 Google V8 引擎中创建一个 utf8 字符串

html5 Liquid CSS 的固定左侧主要内容区域与右侧内容液体

c++ - 模板元编程经验法则

C++ 模板特化 : compile error: "is not a type"

javascript - 替换深色背景和正方形

html - 使页面 curl 的透明图像与纯色背景一起使用

jquery - 带有两个 div 的 slideToggle

javascript - 滚动到名称为 "foo"的随机类