如何渲染幾萬條數(shù)據(jù)不卡住頁面?也就是說不能一次性將幾萬條數(shù)據(jù)都渲染出來对蒲,而是應該一次渲染一部分DOM钩蚊,需要用到requestAnimationFrame贡翘、createDocumentFragment兩個api。
1砰逻、window.requestAnimationFrame()
window.requestAnimationFrame()告訴瀏覽器——你希望執(zhí)行一個動畫鸣驱,并且要求瀏覽器在下次重繪之前調(diào)用指定的回調(diào)函數(shù)更新動畫。該方法需要傳入一個回調(diào)函數(shù)作為參數(shù)蝠咆,該回調(diào)函數(shù)會在瀏覽器下一次重繪之前執(zhí)行丐巫。
語法
window.requestAnimationFrame(callback);
參數(shù)
callback
下一次重繪之前更新動畫幀所調(diào)用的函數(shù)(即上面所說的回調(diào)函數(shù))。該回調(diào)函數(shù)會被傳入DOMHighResTimeStamp參數(shù)勺美,該參數(shù)與performance.now()的返回值相同递胧,它表示requestAnimationFrame() 開始去執(zhí)行回調(diào)函數(shù)的時刻。
返回值
一個 long 整數(shù)赡茸,請求 ID 缎脾,是回調(diào)列表中唯一的標識。是個非零值占卧,沒別的意義遗菠。你可以傳這個值給 window.cancelAnimationFrame() 以取消回調(diào)函數(shù)。
參考:MDN 其他詳細介紹請?zhí)D(zhuǎn)MDN
2华蜒、document.createDocumentFragment()
語法
let fragment = document.createDocumentFragment();
描述
[DocumentFragments](https://developer.mozilla.org/en-US/docs/DOM/DocumentFragment "DOM/DocumentFragments")
是DOM節(jié)點辙纬。它們不是主DOM樹的一部分。通常的用例是創(chuàng)建文檔片段叭喜,將元素附加到文檔片段贺拣,然后將文檔片段附加到DOM樹。在DOM樹中捂蕴,文檔片段被其所有的子元素所代替譬涡。
因為文檔片段存在于內(nèi)存中,并不在DOM樹中啥辨,所以將子元素插入到文檔片段時不會引起頁面回流(對元素位置和幾何上的計算)涡匀。因此,使用文檔片段通常會帶來更好的性能溉知。
模擬代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<ul>控件</ul>
<script>
setTimeout(() => {
// 插入十萬條數(shù)據(jù)
const total = 100000
// 一次插入 20 條陨瘩,如果覺得性能不好就減少
const once = 20
// 渲染數(shù)據(jù)總共需要幾次
const loopCount = total / once
let countOfRender = 0
let ul = document.querySelector("ul");
function add() {
// 優(yōu)化性能,插入不會造成回流
const fragment = document.createDocumentFragment();
for (let i = 0; i < once; i++) {
const li = document.createElement("li");
li.innerText = Math.floor(Math.random() * total);
fragment.appendChild(li);
}
ul.appendChild(fragment);
countOfRender += 1;
loop();
}
function loop() {
if (countOfRender < loopCount) {
window.requestAnimationFrame(add);
}
}
loop();
}, 0);
</script>
</body>
</html>