我正在开发一个小型网络实用程序,用于显示一些数据库表中的一些数据。
我的实用程序在 FF、Safari、Chrome... 上运行良好,但 IE8 上的内存管理非常糟糕。最大的 JSON 请求将返回信息以在浏览器的表格中创建大约 5,000 行(表格中的 3 列)。
我正在使用 jQuery 获取数据(通过 getJSON)。要删除旧表/现有表,我只需执行 $('#my_table_tbody').empty()
。要将新信息添加到表中,在 getJSON 回调中,我只是将我正在创建的每个表行附加到一个变量,然后一旦我拥有它们,我正在使用 $('#my_table_tbody') .append(myVar)
将其添加到现有的 tbody。我没有在创建表行时添加它们,因为这似乎比一次添加它们要慢得多。
对于尝试向 DOM 添加数千行数据的人应该做什么,有没有人有任何建议?我想远离分页,但我想知道我是否别无选择。
更新 1 所以这是我在 innerHTML 建议之后尝试的代码:
/* Assuming a div called 'main_area' holds the table */ document.getElementById('main_area').innerHTML = ''; $.getJSON("my_server", {my: JSON, args: are, in: here}, function(j) { var mylength = j.length; var k =0; var tmpText = ''; tmpText += /* Add the table, thead stuff, and tbody tags here */; for (k = mylength - 1; k >= 0; k--) { /* stack overflow wont let me type greater than & less than signs here, so just assume that they are there. */ tmpText += 'tr class="' + j[k].row_class . '" td class="col1_class" ' + j[k].col1 + ' /td td class="col2_class" ' + j[k].col2 + ' /td td class="col3_class" ' + j[k].col3 + ' /td /tr'; } document.getElementById('main_area').innerHTML = tmpText; }
这就是它的要点。我也试过只使用 $.get 请求,让服务器发送格式化的 HTML,然后在 innerHTML 中设置它(即 document.getElementById('main_area').innerHTML = j;
).
感谢大家的回复。你们都愿意提供帮助,这让我很感动。
最佳答案
var tmpText = [];
for (k = mylength - 1; k >= 0; k--)
{
/* stack overflow wont let me type greater than & less than signs here, so just assume that they are there. */
tmpText.push('anything you want')
tmpText.push( 'tr class="' + j[k].row_class . '" td class="col1_class" ' + j[k].col1 + ' /td td class="col2_class" ' + j[k].col2 + ' /td td class="col3_class" ' + j[k].col3 + ' /td /tr';)
}
$('#main_area').html(tmpText.join(''))
}
你不需要 document.getElementById('main_area').innerHTML = '';
这个方法是压入数组,然后加入并使用jquery html函数更新。这是我知道的最快的方法。抱歉这里的格式 - 这是我的第一篇文章,我想我会在这里回馈一些东西给 stackoverflow。
关于javascript - IE8 的 DOM 内存问题(插入大量 JSON 数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2555066/