自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

15個值得開發(fā)者關(guān)注的jQuery開發(fā)技巧和心得

開發(fā) 前端
在這篇文章中,我們將介紹15個讓你的jQuery更加有效的技巧,大部分關(guān)于性能提升的,希望大家能夠喜歡!

51CTO推薦專題:jQuery從入門到精通

1. 盡量使用***版本的jQuery類庫

jQuery項(xiàng)目中使用了大量的創(chuàng)新。***的方法來提高性能就是使用***版本的jQuery。每一個新的版本都包含了優(yōu)化的bug修復(fù)。對我們來說唯一要干的就是修改tag,何樂而不為呢?

我們也可以使用免費(fèi)的CDN服務(wù),例如, Google來存放jQuery類庫。

  1. <!-- Include a specific version of jQuery --> 
  2. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> 
  3. <!-- Include the latest version in the 1.6 branch --> 
  4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script> 

2. 使用簡單的選擇器

直 到最近,返回DOM元素的方式都是解析選擇器字符串,javascript循環(huán)和內(nèi)建的javascript API例如,getElementbyId(),getElementsByTagName(),getElementsByClassName()三種 方式的整合使用。但是現(xiàn)代瀏覽器都開始支持querySelectorAll(),這個方法能夠理解CSS查詢器,而且能帶來顯著的性能提升。

然而,我們應(yīng)該避免使用復(fù)雜的選擇器返回元素。更不用說很多用戶使用老版本的瀏覽器,強(qiáng)迫jQuery去處理DOM樹。這個方式非常慢。

  1. $('li[data-selected="true"] a') // Fancy, but slow   
  2. $('li.selected a')  // Better   
  3. $('#elem')  // Best 

選擇id是最快速的方式。如果你需要使用class名稱, 那么你***帶上tag名稱,這樣會更快些。特別是在老瀏覽器和移動設(shè)備上。

訪問DOM是javascript應(yīng)用最慢的方式 ,因此盡量少使用。使用變量去保存選擇器,這樣會使用cache來保存。性能更好。

  1. var buttons = $('#navigation a.button');  // Some prefer prefixing their jQuery variables with $:   
  2. var $buttons = $('#navigation a.button'); 

另 外一個值得做的是jQuery給了你很多的額外便利選擇器 ,例如,:visible,:hidden,:animated還有其它,這些不是合法的CSS3選擇器。結(jié)果是你使用這些類庫就不能有效地利用 querySelectorAll()方法。為了彌補(bǔ)這個問題,你需要先選擇元素,再過濾,如下:

  1. $('a.button:animated'); // Does not use querySelectorAll()   
  2. $('a.button').filter(':animated');  // Uses it 

3. 數(shù)組方式使用jQuery對象

運(yùn)行選擇器的結(jié)果是一個jQuery對象。然而,jQuery類庫讓你感覺你正在使用一個定義了index和長度的數(shù)組。

  1. // Selecting all the navigation buttons:  
  2. var buttons = $('#navigation a.button');  
  3.  
  4. // We can loop though the collection:  
  5. for(var i=0;i<buttons.length;i++){  
  6.     console.log(buttons[i]);    // A DOM element, not a jQuery object  
  7. }  
  8.  
  9. // We can even slice it:  
  10. var firstFour = buttons.slice(0,4); 

如果性能是你關(guān)注的,那么使用簡單for或者while循環(huán)來處理,而不是$.each(),這樣能使你的代碼更快。

檢查長度也是一個檢查你的collection是否含有元素的方式。

  1. if(buttons){    // This is always true  
  2.     // Do something  
  3. }  
  4.  
  5. if(buttons.length){ // True only if buttons contains elements  
  6.     // Do something  

4. 選擇器屬性

jQuery提供了一個屬性,這個屬性顯示了用來做鏈?zhǔn)降倪x擇器。

  1. $('#container li:first-child').selector    // #container li:first-child  
  2. $('#container li').filter(':first-child').selector    // #container li.filter(:first-child) 

雖然上面的例子針對同樣的元素,選擇器則完全不一樣。第二個實(shí)際上是非法的,你不可以使用它來創(chuàng)建一個對象。只能用來顯示filter方法是用來縮小collection。

5. 創(chuàng)建一個空的jQuery對象

創(chuàng)建一個新的jQuery空間能極大的減小開銷。有時候,你可能需要創(chuàng)建一個空的對象,然后使用add()方法添加對象。

  1. var container = $([]);   
  2. container.add(another_element); 

這也是quickEach方法的基礎(chǔ),你可以使用這種更快的方式而非each()。

6. 選擇一個隨機(jī)元素

上面我提到過,jQuery添加它自己的選擇器過濾。除了類庫,你可以添加自己的過濾器。只需要添加一個新的方法到$.expr[':']對象。一個非常棒的使用方式是Waldek Mastykarz的博客中提到的:創(chuàng)建一個用來返回隨機(jī)元素的選擇器。你可以修改下面代碼:

  1. (function($){  
  2.     var random = 0;  
  3.  
  4.     $.expr[':'].random = function(a, i, m, r) {  
  5.         if (i == 0) {  
  6.             random = Math.floor(Math.random() * r.length);  
  7.         }  
  8.         return i == random;  
  9.     };  
  10.  
  11. })(jQuery);  
  12.  
  13. // This is how you use it:  
  14. $('li:random').addClass('glow'); 

7. 使用CSS Hooks

CSS hooks API是提供開發(fā)人員得到和設(shè)置特定的CSS數(shù)值的方法。使用它,你可以隱藏瀏覽器特定的執(zhí)行并且使用一個統(tǒng)一的界面來存取特定的屬性。

  1. $.cssHooks['borderRadius'] = {  
  2.         get: function(elem, computed, extra){  
  3.             // Depending on the browser, read the value of  
  4.             // -moz-border-radius, -webkit-border-radius or border-radius  
  5.         },  
  6.         set: function(elem, value){  
  7.             // Set the appropriate CSS3 property  
  8.         }  
  9. };  
  10.  
  11. // Use it without worrying which property the browser actually understands:  
  12. $('#rect').css('borderRadius',5); 

更好的在于,人們已經(jīng)創(chuàng)建了一個支持CSS hooks類庫

8. 使用自定義的刪除方法

你可能聽到過jQuery的刪除插件,它能夠允許你給你的動畫添加特效。唯一的缺點(diǎn)是你的訪問者需要加載另外一個javascript文件。幸運(yùn)的是,你可以簡單的從插件拷貝效果,并且添加到j(luò)Query.easing對象中,如下:

  1. $.easing.easeInOutQuad = function (x, t, b, c, d) {  
  2.     if ((t/=d/2) < 1) return c/2*t*t + b;  
  3.     return -c/2 * ((--t)*(t-2) - 1) + b;  
  4. };  
  5.  
  6. // To use it:  
  7. $('#elem').animate({width:200},'slow','easeInOutQuad'); 

9. $.proxy()

使用callback方法的缺點(diǎn)之一是當(dāng)執(zhí)行類庫中的方法后,context被設(shè)置到另外一個元素,例如:

  1. <div id="panel" style="display:none"> 
  2.     <button>Close</button> 
  3. </div> 

執(zhí)行下面代碼:

  1. $('#panel').fadeIn(function(){  
  2.     // this points to #panel  
  3.     $('#panel button').click(function(){  
  4.         // this points to the button  
  5.         $(this).fadeOut();  
  6.     });  
  7. }); 

你將遇到問題,button會消失,不是panel。使用$.proxy方法,你可以這樣書寫代碼:

  1. $('#panel').fadeIn(function(){  
  2.     // Using $.proxy to bind this:  
  3.  
  4.     $('#panel button').click($.proxy(function(){  
  5.         // this points to #panel  
  6.         $(this).fadeOut();  
  7.     },this));  
  8. }); 

這樣才正確的執(zhí)行。$.proxy方法接受兩個參數(shù),你最初的方法,還有context。這里閱讀更多$.proxy in the docs.。

10. 判斷頁面是否太過復(fù)雜

一個非常簡單的道理,約復(fù)雜的頁面,加載的速度越慢。你可以使用下面代碼檢查一下你的頁面內(nèi)容:

  1. console.log( $('*').length ); 

以上代碼返回的數(shù)值越小,網(wǎng)頁加載速度越快。你可以考慮通過刪除無用多余的元素來優(yōu)化你的代碼

11. 將你的代碼轉(zhuǎn)化成jQuery插件

如果你要花一定得時間去開發(fā)一段jQuery代碼,那么你可以考慮將代碼變成插件。這將能夠幫助你重用代碼,并且能夠有效的幫助你組織代碼。創(chuàng)建一個插件代碼如下:

  1. (function($){  
  2.     $.fn.yourPluginName = function(){  
  3.         // Your code goes here  
  4.         return this;  
  5.     };  
  6. })(jQuery); 

你可以在這里閱讀更多開發(fā)教程。

12. 設(shè)置全局AJAX為缺省

如果你開發(fā)ajax程序的話,你肯定需要有”加載中“之類的顯示告知用戶,ajax正在進(jìn)行,我們可以使用如下代碼統(tǒng)一管理,如下:

  1. // ajaxSetup is useful for setting general defaults:  
  2. $.ajaxSetup({  
  3.     url            : '/ajax/',  
  4.     dataType    : 'json'  
  5. });  
  6.  
  7. $.ajaxStart(function(){  
  8.     showIndicator();  
  9.     disableButtons();  
  10. });  
  11.  
  12. $.ajaxComplete(function(){  
  13.     hideIndicator();  
  14.     enableButtons();  
  15. });  
  16.  
  17. /*  
  18.     // Additional methods you can use:  
  19.     $.ajaxStop();  
  20.     $.ajaxError();  
  21.     $.ajaxSuccess();  
  22.     $.ajaxSend();  
  23. */ 

13. 在動畫中使用delay()方法

鏈?zhǔn)降膭赢嬓Ч莏Query的強(qiáng)大之處。但是有一個忽略了的細(xì)節(jié)就是你可以在動畫之間加上delays,如下:

  1. // This is wrong:  
  2. $('#elem').animate({width:200},function(){  
  3.     setTimeout(function(){  
  4.         $('#elem').animate({marginTop:100});  
  5.     },2000);  
  6. });  
  7.  
  8. // Do it like this:  
  9. $('#elem').animate({width:200}).delay(2000).animate({marginTop:100}); 

jQuery動畫幫了我們大忙,否則我們得自己處理一堆的細(xì)節(jié),設(shè)置timtout,處理屬性值,跟蹤動畫變化等等。

大家可以參考這個文章:jQuery animations

14. 合理利用HTML5的Data屬性

HTML5的data屬性可以幫助我們插入數(shù)據(jù)。特別合適前后端的數(shù)據(jù)交換。jQuery近來發(fā)布的data()方法,可以有效的利用HTML5的屬性,來自動得到數(shù)據(jù)。下面是個例子:

  1. <div id="d1" data-role="page" data-last-value="43" data-hidden="true" 
  2.     data-options='{"name":"John"}'> 
  3. </div> 

為了存取數(shù)據(jù)你需要調(diào)用如下代碼:

  1. $("#d1").data("role");          // "page"  
  2. $("#d1").data("lastValue");     // 43  
  3. $("#d1").data("hidden");        // true;  
  4. $("#d1").data("options").name;  // "John"; 

15. 本地存儲和jQuery

本地存儲是一個超級簡單的API。簡單的添加你的數(shù)據(jù)到localStorage全局屬性中:

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

但是對于老的瀏覽器來說,這個不是個好消息。因?yàn)樗麄儾恢С?。但是我們可以使用jQuery的插件來提供支持一旦本地存儲不能用的話。這種方式可以使得本地存儲功能正常工作。

以上是我們介紹的15個jQuery的開發(fā)技巧,如果你有更多的技巧和評論,請在下面給我們留言, 謝謝支持!

原文:http://www.gbin1.com/technology/jquery/20111116jquery15tips/

【編輯推薦】

  1. 使用HTML 5、CSS3和jQuery增強(qiáng)網(wǎng)站用戶體驗(yàn)
  2. 使用jQuery設(shè)計數(shù)據(jù)表格之設(shè)計表格基類
  3. 自己動手開發(fā)jQuery插件
  4. jQuery插件開發(fā)實(shí)戰(zhàn)場
  5. 50個必備的實(shí)用jQuery代碼段
責(zé)任編輯:陳貽新 來源: GBin1.com
相關(guān)推薦

2012-08-20 09:57:15

新興平臺汽車智能家電

2019-01-02 08:35:42

開發(fā)者技能博客

2018-01-08 10:39:17

前端技術(shù)框架

2013-09-27 09:50:23

2018-01-04 22:17:05

Python開源工具

2014-11-14 09:41:53

Java工具

2018-01-03 09:48:51

Python開源庫工具

2021-10-11 08:20:30

Javascript 高階函數(shù)前端

2021-05-10 10:01:04

JavaScript開發(fā)技巧

2010-09-03 13:54:44

PHP開發(fā)工具

2023-10-16 08:00:00

2021-01-27 09:00:00

開發(fā)PHP框架

2015-12-08 13:25:39

2019-09-10 09:10:45

開發(fā)者技能Java

2013-12-24 09:24:01

開發(fā)者

2025-03-31 01:00:00

AI編碼趨勢

2025-04-17 08:36:30

2015-03-25 11:12:35

iOS開發(fā)

2015-04-14 09:33:17

WatchKitAPP

2016-05-04 10:00:04

混合開發(fā)移動博客
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號