如何渲染幾萬條數據並不卡住界面?


如何渲染幾萬條數據並不卡住界面?

如何在不卡住頁面的情況下渲染數據,也就是說不能一次性將幾萬條 都渲染出來,而應該一次渲染部分 DOM,那么就可以通過 requestAnimationFrame 來 每 16 ms 刷新一次。

<!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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM