一、jQuery.buildFragment使用方法
1、參數
jQuery.buildFragment( args, context, scripts );2、返回值
return { fragment: fragment, cacheable: cacheable };
二、思路分析
1、處理context參數
根據傳入到context參數值的不同,確保context為文檔根節點document
2、限制可緩存條件
2.1、字符串小于512字節
2.2、字符串不存在option標簽(克隆option標簽會丟失選中狀態,因此不緩存)
2.3、字符串不存在<object>,<embed>標簽(IE 6不能把<object>,<embed>標簽嵌入到文檔碎片中)
2.4、字符串不存在checked屬性(只針對克隆擁有checked屬性節點時丟失選中狀態的瀏覽器,如:Safria)
2.5、字符串中不存在html5標簽(只針對不支持html5標簽的瀏覽器)
3、處理args數組
通過jQuery.clean函數格式化處理數組項字符串,并生成dom節點添加到文檔碎片中
4、判斷緩存值
如果緩存值為由clean函數處理的文檔碎片,則數組項字符串略過clean函數處理
5、返回值
函數返回一個對象,保存文檔碎片和可緩存狀態
三、源碼注釋分析
【基于jQuery1.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 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
// 根據參數context值的不同,確保context為文檔根節點document
// jQuery1.8.0版本以后代碼相對于之前版本有很大改進,以下是改進地方:
// 針對context參數值為undefined, jQuery對象,DOM元素節點情況改進代碼
// 解決了1.8.0版本中context參數為文檔片段(#document-fragment)的bug
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
// html字符串小于512字節
// 克隆option標簽會丟失選中狀態,因此不緩存
// IE 6不能把<object>,<embed>標簽嵌入到文檔碎片中
// WebKit瀏覽器(如:Safria)克隆擁有checked屬性節點時,也會丟失選中狀態,因此不緩存,google最新版本不存在該bug