乐趣区

如何做到10万条数据渲染不卡顿

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 MAX_ONCE = 20;
        // 渲染数据需要的次数
        const loopCount = total / MAX_ONCE;
        let countOfRender = 0;
        let el = document.querySelector("ul");
        function add() {
          // 优化,不允许插入数据引起回流
          const fragment = document.createDocumentFragment();
          for (let i = 0; i < MAX_ONCE; i++) {const li = document.createElement("li");
            li.innerText = `${i} + ${Math.floor(Math.random() * total)}`;
            fragment.appendChild(li);
          }
          el.appendChild(fragment);
          countOfRender += 1;
          loop();}

        function loop() {if (countOfRender < loopCount) {window.requestAnimationFrame(add);
          }
        }
        loop();}, 0);
    </script>
  </body>
</html>
退出移动版