requestAnimationFrame解決萬級別數據插入

requestAnimationFrame

<!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(() => {
        // 插入十萬條數據
        const total = 100000;
        // 一次插入 20 條,若是以爲性能很差就減小
        const once = 20;
        // 渲染數據總共須要幾回
        const loopCount = total / once;
        let countOfRender = 0
        let ul = document.querySelector("ul");
    function add() {
        // 優化性能,插入不會形成迴流
        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>複製代碼
相關文章
相關標籤/搜索