妙味——文档碎片

document.createDocumentFragment()

1、普通创建方法:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<script>
window.onload=function(){
    var oBtn = document.getElementById('btn');
    var oUl = document.getElementById('ul1');
    
    oBtn.onclick=function(){
        var iStart = new Date().getTime();
        var i = 0;

        for(i=0;i<10000;i++){
            var oLi = document.createElement('li');

            oUl.appendChild(oLi);
        }

        alert(new Date().getTime()-iStart);
    };
}
</script>
</head>
<body>
    <input type="button" value="普通方式" id="btn" />
    <ul id="ul1"></ul>
</body>
</html>

2、文档碎片方法:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<script>
window.onload=function(){
    var oBtn = document.getElementById('btn');
    var oUl = document.getElementById('ul1');
    
    oBtn.onclick=function(){
        var iStart = new Date().getTime();
        var oFrag = document.createDocumentFragment();    //创建文档碎片用
        var i = 0;

        for(i=0;i<10000;i++){
            var oLi = document.createElement('li');

            oFrag.appendChild(oLi);
        }

        oUl.appendChild(oFrag);

        alert(new Date().getTime()-iStart);
    };
}
</script>
</head>
<body>
    <input type="button" value="碎片方式" id="btn" />
    <ul id="ul1"></ul>
</body>
</html>

有时候文档碎片方法反而会影响性能,多用于面试。

posted @ 2013-12-04 20:17  白小虫  阅读(198)  评论(0编辑  收藏  举报