首页 > 解决方案 > 如何在不影响性能的情况下将大量数据加载到数据表中

问题描述

当我加载较少的数据(300 行)时,此脚本工作正常。但是当我尝试加载更多数据(3000 行)时,它会花费更多时间,并且浏览器会显示一些脚本减慢错误。请帮我解决这个问题

HTML表格如下图

<table class="table table-bordered" id="db_new_table">
     <thead>
        <tr>
          <th> Key </th>
           <th> Value </th>
        </tr>
     </thead>
     <tbody>
         //to here loading data from js     
     </tbody>
</table>

我的 JS 脚本如下所示

//Intializing database
    var table_new = $('#db_new_table').DataTable({            
      "bSortClasses": false,           
      "lengthMenu": [ 500, 1000, 1500, 2000 ],
      "pageLength": 500,
      "deferLoading": coutnt,            
    });


//Loading data to datatable   
var j=1;        
$.each((this.data), function(i, key){  
  var tr = '<tr class="table_row" data-id='+j+'> <td>'+ i +'</td> <td>'+ key +'</td> </tr>'; 

  table_new.rows.add($(tr)).draw();            
  j++;
});

标签: javascriptjqueryhtmlperformancedatatables

解决方案


3000 行是浏览器要处理的大量 DOM 元素。您可以尝试使用虚拟滚动来防止浏览器变慢或崩溃。虚拟滚动只会渲染您在屏幕上看到的 DOM 元素并在您滚动时替换数据,而不是添加更多 DOM 元素。

您可以尝试使用此库进行虚拟滚动 https://clusterize.js.org/

如果您的请求花费太多时间,您可能会遇到超时问题。在这种情况下,您可以考虑使用分页或无限滚动


推荐阅读