一棵树

路漫漫其修远兮 吾将上下而求索。

导航

jQuery 性能调优

技巧 #1 - 尽可能多地通过 ID 进行搜索,而不是 CLASS

在 jQuery 代码中两种常见的搜索技术是通过元素的 ID 进行搜索和通过元素的 CLASS 进行搜索。在使用常规 JavaScript 的 JavaScript 库之前,通过 ID 查找页面元素还是相当简单的。可以使用 getElementById() 方法快速找到元素。但是如果没有 JavaScript 库,要查找 CLASS 会更加困难,在必要情况下,我们还通过在其 ID 中进行编码帮助查找。使用 jQuery 时,搜索 CLASS 就像搜索页面上的 ID 一样简单,因此这两个搜索似乎是可互换的。然而实际情况并非如此。通过 ID 搜索比通过 CLASS 搜索要快得多。当通过 ID 进行搜索时,jQuery 实际上仅使用内置的 getElementById() 方法,但通过 CLASS 进行搜索时必须遍历页面上的所有元素,以查找匹配项。很明显,当页面越大并且越复杂时,通过 CLASS 进行搜索会导致响应非常慢,而通过 ID 进行搜索不会随着页面变大而变慢。

技巧 #2 - 提供尽可能多的搜索信息

// Assume there are 50 of these in some giant form, and you need to validate
// these fields before they are submitted, and there are hundreds of other
// elements on the page as well
<input type=text class="notBlank">

// the "bad" way to validate these fields
$(".notBlank").each(function(){
if ($(this).val()=="")
$(this).addClass("error");
});

// the "good" way to validate these fields
$("input.notBlank").each(function(){
if ($(this).val()=="")
$(this).addClass("error");
});

// the "best" way to validate these fields
$("input:text.notBlank").each(function(){
if ($(this).val()=="")
$(this).addClass("error");
});

技巧 #3 - 缓存选择器

var hideable;

$("#ourHideButton").click(function(){
if (hideable)
hideable.hide();
else
hideable = $(".hideable").hide();
});

posted on 2014-11-20 14:11  nxp  阅读(55)  评论(0编辑  收藏  举报