Created
April 24, 2017 12:24
-
-
Save roshanca/964392a5a070a9dc318b4279dc940c1e to your computer and use it in GitHub Desktop.
插入大量 DOM 的优化
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const container = document.getElementById('js-list'); | |
if (!container) { | |
return | |
} | |
const total = 10000 | |
const batchSize = 4 // 每次插入多少个结点,越大越卡 | |
const batchCount = total / batchSize // 插入次数 | |
let batchDone = 0 // 已经完成的批处理个数 | |
function appendItems() { | |
const fragment = document.createDocumentFragment() | |
for (let i = 0; i < batchSize; i++) { | |
const item = document.createElement('li') | |
item.innerText = batchDone * batchSize + i + 1 | |
fragment.appendChild(item) | |
} | |
container.appendChild(fragment) | |
batchDone += 1 | |
doBatchAppend() | |
} | |
function doBatchAppend() { | |
if (batchDone < batchCount) { | |
window.requestAnimationFrame(appendItems) | |
} | |
} | |
// Kickoff | |
doBatchAppend() | |
// Event delegation | |
container.addEventListener('click', function (e) { | |
const target = e.target | |
if (target.tagName === 'LI') { | |
alert(target.innerHTML) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment