DIV CSS 佈局教程網

深入 jQuery 選擇器:執行原理與效能優化
編輯:JQuery特效代碼     

為什麼老前輩都說「能用 ID 就用 ID」?答案藏在 init 裡。搞懂這段流程,寫出來的選擇器自然會快。

先釐清一個誤會

每次呼叫 $(),回傳的其實是 jQuery.prototype.init 的執行個體。很多人疑惑:init 不是 jQuery.fn 的方法嗎?這裡它是被當作建構函式在用。因為 jQuery.fn = jQuery.prototype,加上 JS 物件是引用而非複本,new jQuery、new jQuery.fn、new jQuery.fn.init 產生的子物件在結構上是一致的,差別只在有沒有執行到 init 的邏輯。

init 裡做了什麼

if ( typeof selector == "string" ) {
  // 用正則判斷是 HTML 片段還是 #id
  var match = quickExpr.exec( selector );

  if ( match && (match[1] || !context) ) {
    if ( match[1] ){                       // 是 HTML 片段
      selector = jQuery.clean( [ match[1] ], context );
    } else {                               // 是 $("#id")
      var elem = document.getElementById( match[3] );
      if ( elem ){
        if ( elem.id != match[3] )         // 有同 id 但名稱不符的情況
          return jQuery().find( selector );
        return jQuery( elem );             // 直接 return,後續邏輯全部跳過
      }
      selector = [];
    }
  } else {
    // 非 id 形式:在 context 中或全文搜尋
    return jQuery( context ).find( selector );
  }
}

結論很明確:寫成 $('#id') 時最快,因為它只等於一次原生 getElementById,之後的分支完全不執行。

為什麼 $('#id .className') 比較慢

這種複合寫法走的是 return jQuery(context).find(selector) 這條路。看看 find:

find: function( selector ) {
  var elems = jQuery.map(this, function(elem){
    return jQuery.find( selector, elem );   // 在當前集合的每個元素底下搜尋
  });
  return this.pushStack( /[^+>] [^+>]/.test( selector ) || selector.indexOf("..") > -1 ?
    jQuery.unique( elems ) : elems );       // 必要時去重複
}

jQuery.find('#id .className', document) 會從 document 的第一個子節點開始逐層往下走:遇到 # 比對 id、遇到 . 比對 className,還要處理 >、+ 等組合符號。遍歷量取決於 context 的範圍——context 越大,掃過的節點越多。

優化結論

把兩種寫法擺在一起比:

$('#id .className');      // 一次全文 find,範圍是整個 document
$('#id').find('.className'); // 先 getElementById 直接 return,再只遍歷該容器

後者只做一次 ID 定位就拿到精確範圍,第二次搜尋的起點已經縮小到單一節點。當頁面 DOM 龐大時,差距會很明顯。

因此的原則是:第一層選擇器盡量用 ID,且盡量單純,目的是先把範圍定下來;後續再用 find()、children() 往下鑽。此外,把常用的集合存進變數(例如 var $list = $('#list');)避免重複查詢,在迴圈中尤其關鍵。選擇器的優化只是入門,快取與事件代理才是效能設計的骨幹,那部分留待後續再談。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved