46-解决方案
5.11.2 解决方案
组合多种优化方案:
- 插入一个
<table>
或者<tbody>
代替多个<tr>
元素。 - 使用
.innerHTML
或.html()
代替DOM操纵。 - 用
a[++i]
和.join()
构建数组,代替字符串连接。 - 使用基本的
for
循环代替$.each
。 - 减少名称查找。
优化的结果是如下的新版本代码(使用和前面一样的 esc()
函数):
$(document).ready( function() {
function fillTable( names ) {
//用局部函数名称减少名称查找
var e = esc;
//
var html = [], h = −1;
html[++h] = '<table id="nameTable">';
html[++h] = '<tbody>';
for( var name, i = −1; name = names[++i]; ) {
html[++h] = '<tr><td class="name">';
html[++h] = e(name.first);
html[++h] = ' ';
html[++h] = e(name.last);
html[++h] = '</td><td class="address">';
html[++h] = e(name.street);
html[++h] = '<br />';
html[++h] = e(name.city);
html[++h] = ', ';
html[++h] = e(name.state);
html[++h] = ' ';
html[++h] = e(name.zip);
html[++h] = '</td></tr>';
}
html[++h] = '</tbody>';
html[++h] = '</table>';
$('#container')[0].innerHTML = html.join('');
}
$.getJSON( 'names/names-1000.json', function( json ) {
fillTable( json.names );
});
});
新代码要求文档中的HTML代码改为:
<div id="container">
</div>
在IE 7中的一个测试系统上,新代码仅仅运行0.2秒,而原来的代码运行了7秒。快了34倍!
当然,新代码没有原来的代码那么清晰和简练,但是你的网站访问者永远也不知道或者在意这一回事。他们注意的将是页面加载的速度。