N个提高jQUery技巧
1.从Google Code加载jquery框架,这个可以减轻你的服务器的负担
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('jquery','1.4.2');
//google.setOnLoadCallback(test);
</script>
2.速查表,http://colorcharge.com/jquery/
3.尽量精简JS脚本到最少
4.灵活使用Firebug的函数
<script type="text/javascript">
//google.load('jquery','1.4.2');
//google.setOnLoadCallback(test);
try
{
adddlert('xxxxxxxx');
}
catch(err)
{
// FireBug function
//console.time('list');
//console.timeEnd('list');
//console.trace();
//console.error(err);
//console.log(err);
}
})
</script>
5.减少选择器selector的操作次数
for (i = 0; i < 1000; i++)
{
var myList = $('.myList');
myList.append('This is list item ' + i);
}
-------------------------------------
var myList = $('.myList');
for (i = 0; i < 1000; i++)
{
myList.append('This is list item ' + i);
}
效率差好多
6.尽量少的操作DOM,可以一次写入多行内容,但不要分多次每次写一行
var myList = $('#myList');
for (i=0; i<1000; i++){
myList.append('This is list item ' + i);
}
----------------------------------
var myList = $('.myList');
var myListItems = '';
for (i = 0; i < 1000; i++) {
myListItems += '<li>This is list item ' + i + '</li>';
}
myList.html(myListItems);
7.在DOM写入带tag的内容是,先在外层wrap
//1st
var myList = $('#myList');
var list='';
for (i = 0; i < 1000; i++)
{
list+='<li>This is list item ' + i+'</li>';
//myList.append('<li>This is list item ' + i+'</li>');
}
myList.html(list);
// 2nd
var myDiv=$('.myDiv');
var con='<ul>';
for (i = 0; i < 1000; i++)
{
con+='<li class="'+i+'" id="'+i+'">This is list item ' + i+'</li>';
//myList.append('<li>This is list item ' + i+'</li>');
}
con+='</ul>';
myDiv.html(con);
8.选择器尽量使用ID,而不是Class