davestewart
7/10/2014 - 9:07 AM

jQuery asset queing using promises

jQuery asset queing using promises

<!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>