在這篇文章中,我們將介紹15個讓你的jQuery更加有效的技巧,大部分關于性能提升的,希望大家能夠喜歡!
1. 盡量使用最新版本的jQuery類庫
jQuery項目中使用了大量的創新。最好的方法來提高性能就是使用最新版本的jQuery。每一個新的版本都包含了優化的bug修復。對我們來說唯一要干的就是修改tag,何樂而不為呢?
我們也可以使用免費的CDN服務,例如, Google來存放jQuery類庫。
<!-- 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樹。這個方式非常慢。
$('li[data-selected="true"] a') // Fancy, but slow
$('li.selected a') // Better
$('#elem') // Best
選擇id是最快速的方式。如果你需要使用class名稱, 那么你最好帶上tag名稱,這樣會更快些。特別是在老瀏覽器和移動設備上。
訪問DOM是javascript應用最慢的方式 ,因此盡量少使用。使用變量去保存選擇器,這樣會使用cache來保存。性能更好。
var buttons = $('#navigation a.button'); // Some prefer prefixing their jQuery variables with $:
var $buttons = $('#navigation a.button');
另外一個值得做的是jQuery給了你很多的額外便利選擇器 ,例如,:visible,:hidden,:animated還有其它,這些不是合法的CSS3選擇器。結果是你使用這些類庫就不能有效地利用 querySelectorAll()方法。為了彌補這個問題,你需要先選擇元素,再過濾,如下:
$('a.button:animated'); // Does not use querySelectorAll()
$('a.button').filter(':animated'); // Uses it
3. 數組方式使用jQuery對象
運行選擇器的結果是一個jQuery對象。然而,jQuery類庫讓你感覺你正在使用一個定義了index和長度的數組。
// 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是否含有元素的方式。
if(buttons){ // This is always true
// Do something
}
if(buttons.length){ // True only if buttons contains elements
// Do something
}
4. 選擇器屬性
jQuery提供了一個屬性,這個屬性顯示了用來做鏈式的選擇器。
$('#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()方法添加對象。
var container = $([]);
container.add(another_element);
這也是quickEach方法的基礎,你可以使用這種更快的方式而非each()。
6. 選擇一個隨機元素
上面我提到過,jQuery添加它自己的選擇器過濾。除了類庫,你可以添加自己的過濾器。只需要添加一個新的方法到$.expr[':']對象。一個非常棒的使用方式是Waldek Mastykarz的博客中提到的:創建一個用來返回隨機元素的選擇器。你可以修改下面代碼:
(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數值的方法。使用它,你可以隱藏瀏覽器特定的執行并且使用一個統一的界面來存取特定的屬性。、
$.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類庫