buildFragment是在context上,根据args创建一个div区域。核心部分是调用了clean部分。但是buildFragment添加了cache的部分。如果能cache的话,则直接返回创建好的。
具体情况加下:
jQuery.buildFragment = function( args, context, scripts ) { //传入的html代码段(好几段),上下文,是否有script
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
context = context || document; //处理undefined的情况
context = (context[0] || context).ownerDocument || context[0] || context; //处理jquery set 或者node的情况
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( typeof context.createDocumentFragment === "undefined" ) { //createDocumentFragment常见用法是创建一个空的dom fragment,然后把elem append到fragment上,最后再把fragment append到doc 的DOM tree上
context = document;
}
// 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
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && //保证是小的代码段, 并且associated with main document
first.charAt(0) === "<" && !rnocache.test( first ) && //不是embed等情况
(jQuery.support.checkClone || !rchecked.test( first )) && //允许clone并且没有checked属性
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { //允许h5特性,并且不是h5的那些新特性
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ]; //看看是不是有缓存的结果
cachehit = fragment !== undefined;
}
if ( !fragment ) { //如果jQuery.fragments[]跪了,那么就创建一个空的 dom fragment,然后调用clean
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment; //cache元素,cachehit的存在保证了只cache哪些能cache的元素
}
}
return { fragment: fragment, cacheable: cacheable };
};