Skip to content

Instantly share code, notes, and snippets.

@doKill
Last active August 18, 2018 05:22
Show Gist options
  • Save doKill/cd3bb72c232613f6fd920f0d73ad5f16 to your computer and use it in GitHub Desktop.
Save doKill/cd3bb72c232613f6fd920f0d73ad5f16 to your computer and use it in GitHub Desktop.
页面多节点渲染卡顿解决方式

页面有大量li或者option渲染到页面时,容易出现浏览器卡顿活或卡死的情况,比如有一万个li标签。
以前数据量小时我的做法是:

let _domSTR = "";
data.map(item=>{
    _domSTR += `<li>` + ${item.value} + </li>`;
});
$(#father).append( _domSTR );

然而当下遇到一个渲染多li时卡顿的情况,找了一圈解决方案,最后做个总结:

let _domArray = [];
data.map(item => {
    _domArray.push( `<li> + ${item.value} + </li>` );
});
$(#father).replaceWith( `<ul id="father"> _domSTR.join('') </ul>` );

可以发现有两个区别:

1、渲染拼接的纯字符串 ==> 渲染数组拼接的字符串

2、直接添加到父元素 ==> 直接替换

最后的情况是速度又快又不卡顿。

##补充:

setTimeout(() => {
  // 插入十万条数据
  const total = 10000
  // 一次插入 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment