一、jQuery.buildFragment 使用方法
1、參數:jQuery.buildFragment( args, context, scripts );
2、回傳值:return { fragment: fragment, cacheable: cacheable };
二、思路分析
1、處理 context 參數:依傳入值不同,確保 context 為文件根節點 document。
2、限制可緩存條件:
2.1、字串小於 512 位元組。
2.2、字串不含 option 標籤(複製 option 會遺失選中狀態,故不緩存)。
2.3、字串不含 <object>、<embed> 標籤(IE6 無法把它們嵌入文件片段)。
2.4、字串不含 checked 屬性(針對複製時會遺失選中狀態的瀏覽器,如 Safari)。
2.5、字串不含 HTML5 標籤(針對不支援 HTML5 標籤的瀏覽器)。
3、處理 args 陣列:透過 jQuery.clean 格式化處理每個字串項,並生成 DOM 節點加入文件片段。
4、判斷緩存值:若緩存值已是 clean 處理過的文件片段,則可略過重複的 clean 處理。
5、回傳值:函式回傳一個物件,保存文件片段與可緩存狀態。
三、源碼註解分析(基於 jQuery 1.8.3)
var rnocache = /<(?:script|object|embed|option|style)/i,
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i");
jQuery.fragments = {};
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// 依 context 值不同,確保其為文件根節點 document
// 1.8.0 之後針對 context 為 undefined / jQuery 物件 / DOM 節點做了改進
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// 只緩存「小」的(1/2 KB)且與主文件相關的 HTML 字串
// 複製 option 會遺失選中狀態、IE6 不喜歡 fragment 裡的 object/embed、
// WebKit 複製 checked 屬性時會遺失狀態、IE6/7/8 無法正確重用 HTML5 元素建立的片段
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
cacheable = true; // 符合條件,打上可緩存標記
fragment = jQuery.fragments[ first ]; // 取出緩存值
cachehit = fragment !== undefined; // 是否命中第二次相同內容
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts ); // 用 clean 處理 args 並生成節點
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment; // 僅在命中時更新緩存
}
}
return { fragment: fragment, cacheable: cacheable };
};
簡單來說,buildFragment 是 jQuery 內部把「HTML 字串」批次轉成文件片段的中樞,它會先判斷該字串是否符合可安全緩存的條件,命中緩存就跳過解析,藉此減少重複的 DOM 建立開銷,是 jQuery 效能設計上頗為關鍵的一塊。