為什麼 $('#id') 比 $('#id .className') 快得多?答案藏在 jQuery.fn.init 裡。理解這段流程,就能知道選擇器該怎麼寫才有效率。
每次宣告一個 jQuery 物件,回傳的是 jQuery.prototype.init 物件。很多人會疑惑:init 明明是 jQuery.fn 的方法,怎麼會是建構子?關鍵在於 JavaScript 的原型繼承,加上物件只是引用而非拷貝,所以 new jQuery、new jQuery.fn 與 new jQuery.fn.init 產生的子物件本質上是一樣的,差別只在有沒有執行到 init。
使用選擇器 $(selector, context) 時,就會進入 init(selector, context):
if (typeof selector == "string") {
// 用正則判斷是 HTML 片段還是 #id
var match = quickExpr.exec(selector);
if (match && (match[1] || !context)) {
// 情況 A:selector 是 HTML 程式碼 → 交給 clean 補全
if (match[1]) {
selector = jQuery.clean([match[1]], context);
}
// 情況 B:selector 是 #id
else {
var elem = document.getElementById(match[3]);
if (elem) {
if (elem.id != match[3]) {
return jQuery().find(selector); // id 不唯一,退回全文搜尋
}
return jQuery(elem); // 找到就直接 return
}
selector = [];
}
}
// 情況 C:其他複雜選擇器 → 在 context 中或全文搜尋
else {
return jQuery(context).find(selector);
}
}
因為這種寫法相當於執行一次 getElementById,之後的程序完全不必再跑。這是瀏覽器原生的最佳化路徑,速度遠勝任何遍歷。
以下兩種寫法結果完全相同:
$('#id.className')
$('#id').find('.className')
假設 HTML 是 <div id="id"><span class="className"></span></div>,兩者都會回傳那個 span。但執行效率差很多。
find: function (selector) {
// 對目前物件中的每個元素逐一查找
var elems = jQuery.map(this, function (elem) {
return jQuery.find(selector, elem);
});
// 判斷是否需要去重:selector 含「後代 + 子代」組合或含 ".."(parent)寫法時
return this.pushStack(
/[^>][^>]/.test(selector) || selector.indexOf("..") > -1
? jQuery.unique(elems)
: elems
);
}
關鍵是 jQuery.find(selector, elem):它會從傳入的 elem 的第一個子節點開始往下找,遇到 # 比對 id、遇到 . 比對 className,還要處理 >、+、~ 等組合符號。
所以寫成 $('#id .className') 時,jQuery 會呼叫擴充版的 find('#id .className', document)——從 document 開始往下遍歷整份文件。
拆成兩步之後:
getElementById 就直接 return,沒有任何遍歷。find('.className', divElement),只在那個 div 的範圍內遍歷。如果 document 下有幾千個節點,第二種寫法就省下了幾乎全部的比對次數。
$('.className') 這類全域 class 查詢放在最前面,它會掃過整份文件。$('#list .item span') 會先找出所有 span,再往上驗證祖先,反而更慢。// jQuery
$('#id').find('.className');
// 原生:querySelector 由右至左解析,但瀏覽器已高度最佳化
document.getElementById('id').querySelector('.className');
// 更快的做法:把範圍縮小
var root = document.getElementById('id');
root.getElementsByClassName('className');
現代瀏覽器的 querySelector 在實作上已遠比 2010 年代的 jQuery 高效,但「先把範圍縮小再查」這個原則從來沒變過。