以下代码在以下浏览器中运行缓慢:
- 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/