html 使用promises的jQuery资产排队

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 使用promises的jQuery资产排队相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html>

<html>
<head>
    <title>Image Load</title>
	<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>

<body>


<script>
	
	// image loading methods
		$.loadImage = function(url, onLoad, onError) {
			
			function load(deferred)
			{
				function _onLoad() {
					off();
					onLoad && onLoad(image);
					deferred.resolve(image);
				}
	
				function _onError() {
					off();
					onError && onError(image);
					deferred.reject(image);
				}
	
				function off() {
					image.onload	= null;
					image.onerror	= null;
					image.onabort	= null;
				}
				
				var image		= new Image();
				image.onload	= _onLoad;
				image.onerror	= _onError;
				image.onabort	= _onError;
				image.src		= url;
			};
			
			return $.Deferred(load).promise();
		};
		
		$.loadImages = function(urls, onDone, onFail, onLoad, onError)
		{
			// convert URLs to promises
				var defers = urls.map( function(url) { return $.loadImage(url, onLoad, onError); });
				
			// load images
				return ($
					.when.apply(window, defers)
					.done(onDone)
					.fail(onFail));
		}
	
	// URLs	
		var urls = 
		[
			'/animation/assets/images/objects/car.png',
			'/animation/assets/images/objects/object-cash.gif',
			'/animation/assets/images/objects/office-screen-10.png',
			'/animation/assets/images/objects/van.png'
		];
		
	// queue load handlers
		function onDone(){ console.log('loaded all images'); }
		function onFail(){ console.log('failed to load images'); }
		
	// image load handlers
		function onLoad(image){ console.log('loaded ' + image.src); $('body').append($('<img />').attr('src', image.src))}
		function onError(image){ console.log('could not load ' + image.src); }
	
	// load images
		$.loadImages(urls, onDone, onFail, onLoad, onError);
	
</script>
</body>
</html>

以上是关于html 使用promises的jQuery资产排队的主要内容,如果未能解决你的问题,请参考以下文章

html 加载外部GeoJSON(Promises):添加jQuery

为远程 html 页面从 Android 中的本地资产加载 jQuery

jQuery 里的 Promise

大白话讲解Promise搞懂jquery中的Promise

jQuery的Promise 这里介绍的很详细

如何在 Yii 中缩小除 jQuery 之外的所有资产?