javascript - 如何在不影响性能的情况下将大量数据加载到数据表中
问题描述
当我加载较少的数据(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++;
});
解决方案
3000 行是浏览器要处理的大量 DOM 元素。您可以尝试使用虚拟滚动来防止浏览器变慢或崩溃。虚拟滚动只会渲染您在屏幕上看到的 DOM 元素并在您滚动时替换数据,而不是添加更多 DOM 元素。
您可以尝试使用此库进行虚拟滚动 https://clusterize.js.org/
如果您的请求花费太多时间,您可能会遇到超时问题。在这种情况下,您可以考虑使用分页或无限滚动
推荐阅读
- javascript - Javascript 基础
- c# - 将 datagridview 与来自 LINQ 查询的数据绑定
- z3py - Python Z3 和 concurrent.futures
- mysql - SQL Alchemy 更新时间在 Alembic 修订版中不起作用
- angular - Angular 6中的内联可编辑对象列表
- redirect - ZF3 redirect()->toUrl() 不重定向
- elixir - 使用 DecorateX 计算虚拟字段的值
- google-cloud-memorystore - 如何禁用客户端超时?
- javascript - 如何将所有 li 从无序列表传递到 div 除了单击 li
- javascript - 如何返回 Observable
在 Angular 6 中的受保护路由上的 canActivate