zoukankan      html  css  js  c++  java
  • 妙味——文档碎片

    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>

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

    高否?富否?帅否? 否? 滚去学习!
  • 相关阅读:
    爱摘苹果的小明
    盗梦空间
    九九乘法表
    谁是最好的Coder
    画图
    黑色帽子
    a letter and a number
    运维开发面试题
    python 守护进程daemon
    kubernets 应用部署
  • 原文地址:https://www.cnblogs.com/baixc/p/3458288.html
Copyright © 2011-2022 走看看