15个值得开发人员关注的jQuery开发技巧和心得 .

本文介绍了15个让jQuery更高效的技巧,重点在性能优化,包括使用最新版本的jQuery、简单选择器、数组方式使用jQuery对象等。

本文来自:http://blog.youkuaiyun.com/dinglang_2009/article/details/6998296

在这篇文章中,我们将介绍15个让你的jQuery更加有效的技巧,大部分关于性能提升的,希望大家能够喜欢!

1. 尽量使用最新版本的jQuery类库

jQuery项目中使用了大量的创新。最好的方法来提高性能就是使用最新版本的jQuery。每一个新的版本都包含了优化的bug修复。对我们来说唯一要干的就是修改tag,何乐而不为呢?

我们也可以使用免费的CDN服务,例如, Google来存放jQuery类库。

  1. <!--IncludeaspecificversionofjQuery-->
  2. <scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
  3. <!--Includethelatestversioninthe1.6branch-->
  4. <scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<!-- Include a specific version of jQuery --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <!-- Include the latest version in the 1.6 branch --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
2. 使用简单的选择器

直到最近,返回DOM元素的方式都是解析选择器字符串,javascript循环和内建的javascript API,例如, getElementbyId(),getElementsByTagName(),getElementsByClassName()三种方式的整合使用。但是现代浏览器都开始支持querySelectorAll(),这个方法能够理解CSS查询器,而且能带来显著的性能提升

然而,我们应该避免使用复杂的选择器返回元素。更不用说很多用户使用老版本的浏览器,强迫jQuery去处理DOM树。这个方式非常慢。

[javascript] view plain copy print ?
  1. $('li[data-selected="true"]a')//Fancy,butslow
  2. $('li.selecteda')//Better
  3. $('#elem')//Best
$('li[data-selected="true"] a') // Fancy, but slow $('li.selected a') // Better $('#elem') // Best
选择id是最快速的方式。如果你需要使用class名称, 那么你最好带上tag名称,这样会更快些。特别是在老浏览器和移动设备上。

访问DOM是javascript应用最慢的方式 ,因此尽量少使用。使用变量去保存选择器,这样会使用cache来保存。性能更好。

[javascript] view plain copy print ?
  1. varbuttons=$('#navigationa.button');//SomepreferprefixingtheirjQueryvariableswith$:
  2. var$buttons=$('#navigationa.button');
var buttons = $('#navigation a.button'); // Some prefer prefixing their jQuery variables with $: var $buttons = $('#navigation a.button');
另外一个值得做的是jQuery给了你很多的 额外便利选择器 ,例如,:visible,:hidden,:animated还有其它,这些不是合法的CSS3选择器。结果是你使用这些类库就不能有效地利用 querySelectorAll() 方法。为了弥补这个问题,你需要先选择元素,再过滤,如下:
[javascript] view plain copy print ?
  1. $('a.button:animated');//DoesnotusequerySelectorAll()
  2. $('a.button').filter(':animated');//Usesit
$('a.button:animated'); // Does not use querySelectorAll() $('a.button').filter(':animated'); // Uses it
3. 数组方式使用jQuery对象

运行选择器的结果是一个jQuery对象。然而,jQuery类库让你感觉你正在使用一个定义了index和长度的数组。

[javascript] view plain copy print ?
  1. //Selectingallthenavigationbuttons:
  2. varbuttons=$('#navigationa.button');
  3. //Wecanloopthoughthecollection:
  4. for(vari=0;i<buttons.length;i++){
  5. console.log(buttons[i]);//ADOMelement,notajQueryobject
  6. }
  7. //Wecanevensliceit:
  8. varfirstFour=buttons.slice(0,4);
// Selecting all the navigation buttons: var buttons = $('#navigation a.button'); // We can loop though the collection: for(var i=0;i<buttons.length;i++){ console.log(buttons[i]); // A DOM element, not a jQuery object } // We can even slice it: var firstFour = buttons.slice(0,4);
如果性能是你关注的,那么使用简单for或者while循环来处理,而不是$.each(),这样能使 你的代码更快

检查长度也是一个检查你的collection是否含有元素的方式。

[javascript] view plain copy print ?
  1. if(buttons){//Thisisalwaystrue
  2. //Dosomething
  3. }
  4. if(buttons.length){//Trueonlyifbuttonscontainselements
  5. //Dosomething
  6. }
if(buttons){ // This is always true // Do something } if(buttons.length){ // True only if buttons contains elements // Do something }
4. 选择器属性

jQuery提供了一个属性,这个属性显示了用来做链式的选择器。

[javascript] view plain copy print ?
  1. $('#containerli:first-child').selector//#containerli:first-child
  2. $('#containerli').filter(':first-child').selector//#containerli.filter(:first-child)
$('#container li:first-child').selector // #container li:first-child $('#container li').filter(':first-child').selector // #container li.filter(:first-child)
虽然上面的例子针对同样的元素,选择器则完全不一样。第二个实际上是非法的,你不可以使用它来创建一个对象。只能用来显示filter方法是用来缩小collection。

5. 创建一个空的jQuery对象

创建一个新的jQuery空间能极大的减小开销。有时候,你可能需要创建一个空的对象,然后使用add()方法添加对象。

[javascript] view plain copy print ?
  1. varcontainer=$([]);
  2. container.add(another_element);
var container = $([]); container.add(another_element);
这也是 quickEach方法的基础,你可以使用这种更快的方式而非each()。

6. 选择一个随机元素

上面我提到过,jQuery添加它自己的选择器过滤。除了类库,你可以添加自己的过滤器。只需要添加一个新的方法到$.expr[':']对象。一个非常棒的使用方式是Waldek Mastykarz的博客中提到的:创建一个用来返回随机元素的选择器。你可以修改下面代码:

[javascript] view plain copy print ?
  1. (function($){
  2. varrandom=0;
  3. $.expr[':'].random=function(a,i,m,r){
  4. if(i==0){
  5. random=Math.floor(Math.random()*r.length);
  6. }
  7. returni==random;
  8. };
  9. })(jQuery);
  10. //Thisishowyouuseit:
  11. $('li:random').addClass('glow');
(function($){ var random = 0; $.expr[':'].random = function(a, i, m, r) { if (i == 0) { random = Math.floor(Math.random() * r.length); } return i == random; }; })(jQuery); // This is how you use it: $('li:random').addClass('glow');
7. 使用CSS Hooks

CSS hooks API是提供开发人员得到和设置特定的CSS数值的方法。使用它,你可以隐藏浏览器特定的执行并且使用一个统一的界面来存取特定的属性。

[javascript] view plain copy print ?
  1. $.cssHooks['borderRadius']={
  2. get:function(elem,computed,extra){
  3. //Dependingonthebrowser,readthevalueof
  4. //-moz-border-radius,-webkit-border-radiusorborder-radius
  5. },
  6. set:function(elem,value){
  7. //SettheappropriateCSS3property
  8. }
  9. };
  10. //Useitwithoutworryingwhichpropertythebrowseractuallyunderstands:
  11. $('#rect').css('borderRadius',5);
$.cssHooks['borderRadius'] = { get: function(elem, computed, extra){ // Depending on the browser, read the value of // -moz-border-radius, -webkit-border-radius or border-radius }, set: function(elem, value){ // Set the appropriate CSS3 property } }; // Use it without worrying which property the browser actually understands: $('#rect').css('borderRadius',5);
更好的在于,人们已经创建了一个支持 CSS hooks类库

8. 使用自定义的删除方法

你可能听到过jQuery的删除插件,它能够允许你给你的动画添加特效。唯一的缺点是你的访问者需要加载另外一个javascript文件。幸运的是,你可以简单的从插件拷贝效果,并且添加到jQuery.easing对象中,如下:

[javascript] view plain copy print ?
  1. $.easing.easeInOutQuad=function(x,t,b,c,d){
  2. if((t/=d/2)<1)returnc/2*t*t+b;
  3. return-c/2*((--t)*(t-2)-1)+b;
  4. };
  5. //Touseit:
  6. $('#elem').animate({width:200},'slow','easeInOutQuad');
$.easing.easeInOutQuad = function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }; // To use it: $('#elem').animate({width:200},'slow','easeInOutQuad');
9. $.proxy()

使用callback方法的缺点之一是当执行类库中的方法后,context被设置到另外一个元素,例如:

  1. <divid="panel"style="display:none">
  2. <button>Close</button>
  3. </div>
<div id="panel" style="display:none"> <button>Close</button> </div>
执行下面代码:
[javascript] view plain copy print ?
  1. $('#panel').fadeIn(function(){
  2. //thispointsto#panel
  3. $('#panelbutton').click(function(){
  4. //thispointstothebutton
  5. $(this).fadeOut();
  6. });
  7. });
$('#panel').fadeIn(function(){ // this points to #panel $('#panel button').click(function(){ // this points to the button $(this).fadeOut(); }); });
你将遇到问题,button会消失,不是panel。使用$.proxy方法,你可以这样书写代码:
[javascript] view plain copy print ?
  1. $('#panel').fadeIn(function(){
  2. //Using$.proxytobindthis:
  3. $('#panelbutton').click($.proxy(function(){
  4. //thispointsto#panel
  5. $(this).fadeOut();
  6. },this));
  7. });
$('#panel').fadeIn(function(){ // Using $.proxy to bind this: $('#panel button').click($.proxy(function(){ // this points to #panel $(this).fadeOut(); },this)); });
这样才正确的执行。$.proxy方法接受两个参数,你最初的方法,还有context。这里阅读更多 $.proxy in the docs.。

10. 判断页面是否太过复杂

一个非常简单的道理,约复杂的页面,加载的速度越慢。你可以使用下面代码检查一下你的页面内容:

[javascript] view plain copy print ?
  1. console.log($('*').length);
console.log( $('*').length );

以上代码返回的数值越小,网页加载速度越快。你可以考虑通过删除无用多余的元素来优化你的代码

11. 将你的代码转化成jQuery插件

如果你要花一定得时间去开发一段jQuery代码,那么你可以考虑将代码变成插件。这将能够帮助你重用代码,并且能够有效的帮助你组织代码。创建一个插件代码如下:

[javascript] view plain copy print ?
  1. (function($){
  2. $.fn.yourPluginName=function(){
  3. //Yourcodegoeshere
  4. returnthis;
  5. };
  6. })(jQuery);
(function($){ $.fn.yourPluginName = function(){ // Your code goes here return this; }; })(jQuery);
你可以在这里阅读更多 开发教程

12. 设置全局AJAX为缺省

如果你开发ajax程序的话,你肯定需要有”加载中“之类的显示告知用户,ajax正在进行,我们可以使用如下代码统一管理,如下:

[javascript] view plain copy print ?
  1. //ajaxSetupisusefulforsettinggeneraldefaults:
  2. $.ajaxSetup({
  3. url:'/ajax/',
  4. dataType:'json'
  5. });
  6. $.ajaxStart(function(){
  7. showIndicator();
  8. disableButtons();
  9. });
  10. $.ajaxComplete(function(){
  11. hideIndicator();
  12. enableButtons();
  13. });
  14. /*
  15. //Additionalmethodsyoucanuse:
  16. $.ajaxStop();
  17. $.ajaxError();
  18. $.ajaxSuccess();
  19. $.ajaxSend();
  20. */
// ajaxSetup is useful for setting general defaults: $.ajaxSetup({ url : '/ajax/', dataType : 'json' }); $.ajaxStart(function(){ showIndicator(); disableButtons(); }); $.ajaxComplete(function(){ hideIndicator(); enableButtons(); }); /* // Additional methods you can use: $.ajaxStop(); $.ajaxError(); $.ajaxSuccess(); $.ajaxSend(); */
详细你可以查看这篇文章 jQuery’s AJAX functionality

13. 在动画中使用delay()方法

链式的动画效果是jQuery的强大之处。但是有一个忽略了的细节就是你可以在动画之间加上delays,如下:

[javascript] view plain copy print ?
  1. //Thisiswrong:
  2. $('#elem').animate({width:200},function(){
  3. setTimeout(function(){
  4. $('#elem').animate({marginTop:100});
  5. },2000);
  6. });
  7. //Doitlikethis:
  8. $('#elem').animate({width:200}).delay(2000).animate({marginTop:100});
// This is wrong: $('#elem').animate({width:200},function(){ setTimeout(function(){ $('#elem').animate({marginTop:100}); },2000); }); // Do it like this: $('#elem').animate({width:200}).delay(2000).animate({marginTop:100});
jQuery动画帮了我们大忙,否则我们得自己处理一堆的细节,设置timtout,处理属性值,跟踪动画变化等等。

大家可以参考这个文章:jQuery animations

14. 合理利用HTML5的Data属性

HTML5的data属性可以帮助我们插入数据。特别合适前后端的数据交换。jQuery近来发布的data()方法,可以有效的利用HTML5的属性,来自动得到数据。下面是个例子:

  1. <divid="d1"data-role="page"data-last-value="43"data-hidden="true"
  2. data-options='{"name":"John"}'>
  3. </div>
<div id="d1" data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'> </div>
为了存取数据你需要调用如下代码:
[javascript] view plain copy print ?
  1. $("#d1").data("role");//"page"
  2. $("#d1").data("lastValue");//43
  3. $("#d1").data("hidden");//true;
  4. $("#d1").data("options").name;//"John";
$("#d1").data("role"); // "page" $("#d1").data("lastValue"); // 43 $("#d1").data("hidden"); // true; $("#d1").data("options").name; // "John";
如果你想看看实际的例子,请参考这篇教程: 使用HTML5和jQuery插件Quicksand实现一个超酷的星际争霸2兵种分类展示效果

data()的jQuery文档:data() in the jQuery docs

15. 本地存储和jQuery

本地存储是一个超级简单的API。简单的添加你的数据到localStorage全局属性中:

localStorage.someData = "This is going to be saved across page refreshes and browser restarts";

但是对于老的浏览器来说,这个不是个好消息。因为他们不支持。但是我们可以使用jQuery的插件来提供支持一旦本地存储不能用的话。这种方式可以使得本地存储功能正常工作。

以上是我们介绍的15个jQuery的开发技巧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值