documentFragment处理性能问题

 

(function(){
        const ndContainer = document.getElementById('js-list');
        if (!ndContainer) {
            return;
        }
    
        const total = 30000;
        const batchSize = 80; // 每批插入的节点次数,越大越卡
        const batchCount = total / batchSize; // 需要批量处理多少次
        let batchDone = 0;  // 已经完成的批处理个数
    
        function appendItems() {
            const fragment = document.createDocumentFragment();
            for (let i = 0; i < batchSize; i++) {
                const ndItem = document.createElement('li');
                ndItem.innerText = (batchDone * batchSize) + i + 1;
                fragment.appendChild(ndItem);
            }
    
            // 每次批处理只修改 1 次 DOM
            ndContainer.appendChild(fragment);
    
            batchDone += 1;
            doBatchAppend();
            if(batchDone == batchCount){
                console.info(new Date());
            }
        }
    
        function doBatchAppend() {
            if (batchDone < batchCount) {
                window.requestAnimationFrame(appendItems);
            }
        }
        console.info(new Date());
        // kickoff
        doBatchAppend();
    
        ndContainer.addEventListener('click', function (e) {
            const target = e.target;
            if (target.tagName === 'LI') {
                alert(target.innerHTML);
            }
        });
    })();

 

posted @ 2017-05-10 16:03  【云】风过无痕  阅读(91)  评论(0编辑  收藏  举报