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 的方法更效率点。

扩展阅读:



共有7 条评论

  1. 1. 头像 fcicq

    既然说到了加速, 再提两个偶以前用过的.
    getXHR = function() { return new XMLHttpRequest; };
    /*@cc_on _d=document;eval(’var document=_d’)@*/

    顺便偷留两个链接… :D
    http://www.fcicq.net/wp/?p=138
    http://www.fcicq.net/wp/?p=579

  2. 2. 头像 Lunatic Sun

    XMLHttpRequest的提速方法和addEvent的提速方法原理是一致的,说起来还真是无聊,大家竟然都没有想到这么简单的方法。

  3. 3. 头像 leeight的马甲

    @fcicq
    这么写为什么会提速呢?
    搞不清楚原理呢

  4. 4. 头像 无语

    真的会提速吗?
    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反而慢了一半

  5. 5. 头像 无语

    在Opera好象一也样…..

  6. 6. Ye's blog

    通过 Dom 方法提高 innerHTML 性能,慅

    JavaScript代码

  7. 7. veeLove.cn » 优化 innerHTML 性能

    [...] 在怿飞看到这方面介绍,对于非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.*/ [...]

发表评论

(必填)

(必填,会为您保密)

评论仅支持“a、abbr、strong、em、blockquote、code”几个简单的标签