在遇到大量数据需要渲染的时候,一次性渲染会阻塞主线程导致页面卡顿,可以用分块渲染提升页面性能,将大量DOM结点的渲染拆分为多个小任务,避免主线程长时间阻塞,减少页面卡顿。
<script setup lang="ts"> import { ref, onMounted } from 'vue' const tableData=ref<any[]>([]) const CHUNK_SIZE=100 const getData=async()=>{ try{ const res=await fetch('/api/mock') if(!res.ok) throw new Error(`请求失败${res.status}`) const data=await res.json() function* chunkGenerate(){ let index=0 while(index<data.length){ yield data.slice(index,index+CHUNK_SIZE) index+=CHUNK_SIZE } } const generator=chunkGenerate() const process=()=>{ const chunk=generator.next() if(!chunk.done){ tableData.value.push(...chunk.value) requestAnimationFrame(process) } } requestAnimationFrame(process) }catch(error){ console.log('error',error) } } getData() </script>requestAnimationFrame是浏览器原生支持的API,浏览器的屏幕刷新率通常是60 帧 / 秒(FPS),也就是每≈16.67ms 会完成一次页面重绘(更新屏幕内容)。requestAnimationFrame(简称 RAF)的作用是:让你的回调函数,精准在 “下一次页面重绘之前” 执行,由浏览器统一调度,而非手动定时(比如setTimeout)。
为什么不能用setTimeout?
- 处理数据的 JS(setTimeout 回调)在「渲染后」执行,处理完数据后,要等下一个 16.67ms 的渲染帧才能显示新数据;
- 每批数据的渲染都被延迟至少 16.67ms,多批叠加后,肉眼会明显感觉到 “数据处理和画面更新不同步”,表现为 “掉帧、卡顿”;
- 更糟的是:如果 setTimeout 的宏任务队列里有其他任务(比如用户点击回调),数据处理会被进一步推迟,渲染延迟更久。
requestAnimationFrame 的执行流程(同步无延迟)
RAF 的回调跳过宏 / 微任务队列,直接被渲染引擎调度到「渲染前」执行