Quantcast
Channel: 火丁笔记 » Javascript
Viewing all articles
Browse latest Browse all 3

优化InnerHTML操作

$
0
0

多数现代浏览器都实现了innerHTML操作,它的方便性让我们爱不释手,但如果使用不当,很容易出现效率问题,本文通过一个例子来说明如何优化innerHTML操作。

例子:我们要实现的效果是当用户点击鼠标的时候,就在旧数据上追加若干新数据。

如果使用标准DOM的话,完整代码如下:

<html>
<head>
<title>test</title>
</head>
<body>
<div>
<p>data<p>
</div>

<script>
document.onmousedown = function() {
    for (var i = 0; i < 10; i++) {
        var p = document.createElement("p");
        p.appendChild(document.createTextNode(Math.random()));

        document.getElementsByTagName('div')[0].appendChild(p);
    }
};
</script>
</body>
</html>

注:一旦结构比较复杂的话,标准DOM需要编写冗长的代码。

如果使用innerHTML的话,部分代码如下:

<script>
document.onmousedown = function() {
    var html = "";

    for (var i = 0; i < 10; i++) {
        html += "<p>" + Math.random() + "<p>";
    }

    document.getElementsByTagName('div')[0].innerHTML += html;
};
</script>

注:innerHTML没有标准DOM中的appendChild,所以使用了『+=』的方式,效率低下。

我们可以结合使用innerHTML和标准DOM,这样二者的优点就兼得了,部分代码如下:

<script>
document.onmousedown = function() {
    var html = "";

    for (var i = 0; i < 10; i++) {
        html += "<p>" + Math.random() + "<p>";
    }

    var temp = document.createElement("div");
    temp.innerHTML = html;

    while (temp.firstChild) {
        document.getElementsByTagName('div')[0].appendChild(temp.firstChild);
    }
};
</script>

注:创建一个元素,然后注入innerHTML,接着在元素上使用标准DOM操作。

还不算完,Asynchronous innerHTML给出了更强悍的解决方法,部分代码如下:

<script>
document.onmousedown = function() {
    var html = "";

    for (var i = 0; i < 10; i++) {
        html += "<p>" + Math.random() + "<p>";
    }

    var temp = document.createElement('div');

    temp.innerHTML = html;

    var frag = document.createDocumentFragment();

    (function() {
        if (temp.firstChild) {
            frag.appendChild(temp.firstChild);
            setTimeout(arguments.callee, 0);
        } else {
            document.getElementsByTagName('div')[0].appendChild(frag);
        }
    })();
};
</script>

注:使用setTimeout防止堵塞浏览器,使用DocumentFragment减少渲染次数。

另:代码在拼接字符串时还可以更快,详见:Fastest way to build an HTML string


Viewing all articles
Browse latest Browse all 3

Latest Images

Pangarap Quotes

Pangarap Quotes

Vimeo 10.7.0 by Vimeo.com, Inc.

Vimeo 10.7.0 by Vimeo.com, Inc.

HANGAD

HANGAD

MAKAKAALAM

MAKAKAALAM

Doodle Jump 3.11.30 by Lima Sky LLC

Doodle Jump 3.11.30 by Lima Sky LLC

Doodle Jump 3.11.30 by Lima Sky LLC

Doodle Jump 3.11.30 by Lima Sky LLC

Trending Articles





Latest Images

Pangarap Quotes

Pangarap Quotes

Vimeo 10.7.0 by Vimeo.com, Inc.

Vimeo 10.7.0 by Vimeo.com, Inc.

HANGAD

HANGAD

MAKAKAALAM

MAKAKAALAM

Doodle Jump 3.11.30 by Lima Sky LLC

Doodle Jump 3.11.30 by Lima Sky LLC

Doodle Jump 3.11.30 by Lima Sky LLC

Doodle Jump 3.11.30 by Lima Sky LLC