前端优化之如何做到渲染几十万条数据不卡帧
<!DOCTYPE html> <html lang="zh"> <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></title> </head> <body> <ul></ul> </body> <script> // createDocumentFragment // requestAnimationFrame // 插入十万条数据 const total = 100000; // 每次插入20条数据 const once = 20; // 插入的数据需要的次数 const loopCount = Math.ceil(total/once); // 渲染的次数 var countRender = 0; // 获取插入的父节点 const ul = document.querySelector('ul'); // 添加数据的方法 function add(){ const fragment = document.createDocumentFragment(); for(let i = 0; i<once; i++){ const li = document.createElement('li'); li.innerHTML = Math.floor(Math.random()*100000); fragment.appendChild(li) } ul.appendChild(fragment); countRender++; loop(); }; function loop(){ if(countRender < loopCount){ window.requestAnimationFrame(add); } }; loop(); </script> </html>