-
-
Save panayotoff/961363f0baeceb60f6f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment