假设我们需要在页面上加载获取到的10万条数据📊,在不采取优化方案的情况下它的耗时为 482 ms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| <div id="container"></div>
<script> const container = document.getElementById('container') const getList = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve() }, 200); }).then(() => { let arr = [] for (let i = 0; i < 100000; i++) { arr[i] = { id: i, text: i } } return arr }) } const renderList = () => { getList().then(res => { console.time('不优化') res.forEach(item => { const div = document.createElement('div') div.innerHTML = `<span>${item.text}</span>` container.appendChild(div) }); console.timeEnd('不优化') }) } </script>
|
如果使用了分页优化后的耗时为212 ms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| const renderList2 = () => { console.time('分页优化') getList().then(res => { const total = res.length const limit = 10000 const page = 0 const totalPage = Math.ceil(total / limit)
const render = (page) => { if(totalPage<= page)return requestAnimationFrame(()=>{ const fragment = document.createDocumentFragment() for (let i = page * limit; i < page * limit + limit; i++) { const item = res[i]; const div = document.createElement('div') div.innerHTML = `<span>${ item.text }</span>` fragment.appendChild(div) } container.appendChild(fragment) render(page + 1) }) } render(page) console.timeEnd('分页优化') }) }
|
如果dom结构更复杂,差距将更大