Comparison of three ways to create elements in DOM

Classic interview questions: Comparison of the efficiency of creating elements:

    // 1.document.write()会导致页面重绘
    // 2.innerHTML是将内容写入某个DOM节点,不会导致页面重绘。
    // 3.innerHTML创建多个元素效率更高,(只要不采取字符串拼接,采取数组形式拼接),结构稍微复杂。
    // 4.createElement()创建多个元素效率略低,但结构更清晰。
  // 1.Document.write() 创建元素 如果页面文档流加载完毕,
      再调用这句话会导致页面重绘
  // 2.innerHTML   
        // 使用拼接字符串效率很慢
        var inner = document.querySelector('.inner');
        // for(var i = 0; i<=100;i++){
    
    
        //     inner.innerHTML += '<a href="#" > 百度</a>'
        // }
        // 采用数组方式效率高
        var arr = [];
        for (var i = 0; i <= 100; i++) {
    
    
            arr.push('<a href="#" > 百度</a>');
        }
        inner.innerHTML = arr.join('');


  // 3.document.createElement()
        var create = document.querySelector('.create');
        var a = document.createElement('a');
        create.appendChild(a);

Guess you like

Origin blog.csdn.net/weixin_47067248/article/details/107469055