jquery源码——buildFragment

24 篇文章 0 订阅
11 篇文章 0 订阅

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 };
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值