如何渲染⼏万条数据并不卡住界⾯

161 阅读1分钟

不能⼀次性将⼏万条都渲染出 来,⽽应该⼀次渲染部分 DOM,那么就可以通过 requestAnimationFrame 来每 16 ms 刷 新⼀次。

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
</head>
<body>
	<ul>控件</ul>
</body>
<script>
    setTimeout(() => {
        const total = 10000
        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 = (i + 1) + countOfRender * once
                    fragment.appendChild(li)
            }
            ul.appendChild(fragment)
            countOfRender += 1
            loop()
        }

        function loop() {
            if (countOfRender < loopCount) {
                    window.requestAnimationFrame(add)
            }
        }
        loop()
    }, 0)
</script>
</html>