使用documentFragment的IE性能不佳 [英] Bad performance IE using documentFragment
问题描述
为了测试DOM操作与innerHTML的对比,我使用了documentFragment
(网页)将10000个href
元素附加到div
元素. Chrome或Firefox的性能尚可,但是在IE(10、9、8)中,它的性能非常差,大约需要 10-12秒 .谁能解释这种差异和/或详细说明提高IE性能的解决方案?
To test DOM manipulation versus innerHTML I deviced this little test method using a documentFragment
(web page) to append 10000 href
elements to a div
element. The performance is ok for Chrome or Firefox, but in IE (10, 9, 8) it's dramatically bad, it takes around 10-12 seconds. Can anyone explain this difference and/or elaborate on a solution to enhance performance for IE?
这是一个 jsfiddle 进行演示.
Here's a jsfiddle demonstrating it.
方法:
function useFragment(){
var frag = document.createDocumentFragment(),
i = 10000,
rval = document.createElement('span');
frag.appendChild(rval);
do {
var optText = 'option '+i
,ref = document.createElement('a')
,zebra = i%2 ? 'zebra' : ''
,islist = true
,isSel = i === 5
;
rval.insertBefore(ref,rval.firstChild);
ref.appendChild(document.createTextNode(optText));
ref.id = 'opt' + i;
ref.className = zebra + (islist && isSel ? ' scrollSelect' : '');
ref.href = '#' + i;
ref.title = optText;
} while (i-->0);
return rval;
}
推荐答案
我已经找到了它:看起来,尽管documentFragment
应该是一个'offline'元素(不属于该元素的元素)实时DOM) IE不会将其视为此类.强制片段真正脱机的方法是在其上附加一些元素,将其display
属性设置为none
,然后将其余元素附加到该元素.完成后,删除display:none
属性,并且documentFragment
可以附加到DOM.
Think I've found it: it looks like, although a documentFragment
should be an 'off line' element (an element that is not part of the live DOM) IE doesn't treat it as such. The way to force the fragment to really be off line is to append some element to it, set its display
property to none
and append the rest of elements to that element. After you are done, remove the display:none
property and the documentFragment
can be appended to the DOM.
它仍然慢了三倍(在我的PC上,它仍然需要大约1-1.5秒,而10000个元素在Chrome/Firefox中大约需要2-300毫秒).因此,对于IE(甚至是版本10),使用innerHTML
向DOM添加一堆元素是更快的方法.我想说,IE仍然是开发人员的噩梦.
It is still three times slower (on my PC it still takes around 1-1.5 seconds, versus around 2-300 ms in Chrome/Firefox for 10000 elements). So, for IE (even version 10), using innerHTML
to add a bunch of elements to the DOM is the faster way. IE remains a developers nightmare, I'd say.
这篇关于使用documentFragment的IE性能不佳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!