Loading tens of thousands of pieces of data at one time, it is required not to block the interface

<!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(() => {
      // Insert 100,000 pieces of data
      const total = 100000
      // Insert 20 items at a time, reduce if you think the performance is not good
      const once = 20
      // It takes a total of several times to render the data
      const loopCount = total / once
      let countOfRender = 0
      let ul = document.querySelector("ul");
      function add() {
        // Optimize performance, insertion will not cause backflow
        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>

Link: https://juejin.im/post/5aa8a07cf265da238a3022a4
Source: Nuggets

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324975587&siteId=291194637