例如,你想动态的创建一组列表元素,千万不要这样做,如下所示:
var top_100_list = [...], // 假设这里是100个独一无二的字符串$mylist = $("#mylist"); // jQuery 选择到元素
for (var i=0, l=top_100_list.length; i $mylist.append("" + top_100_list[i] + " ");}我们应该将整套元素字符串在插入进dom中之前先全部创建好,如下所示:
var top_100_list = [...],$mylist = $("#mylist"), top_100_li = ""; // 这个变量将用来存储我们的列表元素for (var i=0, l=top_100_list.length; i top_100_li += "" + top_100_list[i] + " ";}$mylist.html(top_100_li);注:记得以前还看过一朋友写过这样的代码:for (i = 0; i < 1000; i++) {
var $myList = $('#myList');
$myList.append('This is list item ' + i);
}
呵呵,你应该已经看出问题所在了。既然把#mylist循环获取了1000次!!!
5,冒泡除非在特殊情况下, 否则每一个js事件(例如:click, mouseover等.)都会冒泡到父级节点。
当我们需要给多个元素调用同个函数时这点会很有用。代替这种效率很差的多元素事件监听的方法就是, 你只需向它们的父节点绑定一次。
比如, 我们要为一个拥有很多输入框的表单绑定这样的行为: 当输入框被选中时为它添加一个class
传统的做法是,直接选中input,然后绑定focus等,如下所示:
$("#entryform input").bind("focus", function(){$(this).addClass("selected");}).bind("blur", function(){$(this).removeClass("selected");});当然上面代码能帮我们完成相应的任务,但如果你要寻求更高效的方法,请使用如下代码:
$("#entryform").bind("focus", function(e){var $cell = $(e.target); // e.target 捕捉到触发的目标元素$cell.addClass("selected");}).bind("blur", function(e){var $cell = $(e.target);$cell.removeClass("selected");});通过在父级监听获取焦点和失去焦点的事件,对目标元素进行操作。
在上面代码中,父级元素扮演了一个调度员的角色, 它可以基于目标元素绑定事件。
如果你发现你给很多元素绑定了同一个事件监听, 那么现在的你肯定知道哪里做错了。同理,在Table操作时,我们也可以使用这种方式加以改进代码:普通的方式:
改进方式:$('#myTable td').click(function(){$(this).css('background', 'red');});假设有100个td,在使用普通的方式的时候,你绑定了100个事件。$('#myTable').click(function(e) {
var $clicked = $(e.target);
$clicked.css('background', 'red');
});
在改进方式中,你只为一个元素绑定了1个事件,至于是100个事件的效率高,还是1个事件的效率高,相信你也能自行分辨了。
6,推迟到 $(window).loadjQuery has a very tempting thing for developers, you can hang anything under $(document).ready.
Although $(document).rady is indeed useful, it can be executed when the page is rendered before other elements have been downloaded.
If you find that your page is always loading, it is most likely caused by the $(document).ready function.You can reduce the CPU usage when the page is loading by binding the jQuery function to the $(window).load event.
It will be executed after all html (including$(window).load(function(){// jQuery function initialized after the page is fully loaded.});
Some special effects functions, such as drag and drop, visual effects and animations, preloading hidden images, etc., are suitable for this technology.
7, compress JavaScriptCompress and minimize your JavaScript files.Online compression address: http://dean.edwards.name/packer/
Before compressing, please ensure that your code is standardized, otherwise it may fail. Causes Js error.This concludes jQuery Performance Optimization Guide (2), Guide (3) is in progress....I believe you also have your own ideas, please share them. Email: cssrain@gmail.comEnglish original text:http://www.artzstudio.com/2009/04/jquery-performance-rules/Chinese translation: http://rlog.cn/350 & http://cssrain.cn