function replaceHtml(el, html) {
var oldEl = typeof el === "string" ? document.getElementById(el) : el;
/*@cc_on // 原始的 innerHTML 在 IE 中的性能好一点
oldEl.innerHTML = html;
return oldEl;
@*/
var newEl = oldEl.cloneNode(false);
newEl.innerHTML = html;
oldEl.parentNode.replaceChild(newEl, oldEl);
/* 一旦我们从 DOM 上移除老的元素,则返回新的元素引用。*/
return newEl;
};
此方法大大提高了 innerHTML 在 Firefox 和 Safari 上的性能。replaceHtml() 在 Firefox 2.0.0.6 里 destroy 与 replace 的速度各快了 473 倍以及 50 倍。而在 Safari 3.0.3 beta 上则是 create 100 倍,replace 50 倍。
对于 Opera 也依然有性能提高,只是提高幅度没有上面两种浏览器惊人而已,
唯在 IE 中,则原始的 innerHTML 的方法更效率点。
扩展阅读:
witter:
共有8 条评论
既然说到了加速, 再提两个偶以前用过的.
getXHR = function() { return new XMLHttpRequest; };
/*@cc_on _d=document;eval(‘var document=_d’)@*/
顺便偷留两个链接…
http://www.fcicq.net/wp/?p=138
http://www.fcicq.net/wp/?p=579
XMLHttpRequest的提速方法和addEvent的提速方法原理是一致的,说起来还真是无聊,大家竟然都没有想到这么简单的方法。
@fcicq
这么写为什么会提速呢?
搞不清楚原理呢
真的会提速吗?
function replaceHtml(el, html) {
var oldEl = document.getElementById(el);
var newEl = oldEl.cloneNode(false);
newEl.innerHTML = html;
oldEl.parentNode.replaceChild(newEl, oldEl);
return newEl;
}
function testInnerText(el,a){
document.getElementById(el).innerHTML = a;
}
a随便一段字符串或者掉标签的字符串,循环执行5000次,结果在FF反而慢了一半
在Opera好象一也样…..
éè¿ Dom æ¹æ³æé« innerHTML æ§è½ï¼æ……
JavaScript代码
…
[...] 在怿飞看到这方面介绍,对于非ie的浏览器有效 ?View Code JAVASCRIPTfunction replaceHtml(el, html) { var oldEl = typeof el === "string" ? document.getElementById(el) : el; /*@cc_on // Pure innerHTML is slightly faster in IE oldEl.innerHTML = html; return oldEl; @*/ var newEl = oldEl.cloneNode(false); newEl.innerHTML = html; oldEl.parentNode.replaceChild(newEl, oldEl); /* Since we just removed the old element from the DOM, return a reference to the new element, which can be used to restore variable references. */ return newEl; }; el = replaceHtml(el, newHtml) /*instead of el.innerHTML = newHtml.*/ [...]
oldEl.parentNode.replaceChild(newEl, oldEl);
used to restore variable references. */ return newEl; };