-
-
Save panayotoff/c9af375b3af1196b1d78 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, onAlways, 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) | |
.then(onAlways) | |
.fail(onFail)) | |
} | |
// URLs | |
var urls = | |
[ | |
'http://ivayloyovchev.com/pulsepro/data/img/gallery/lifestyle-fashion/IMG_0109_.jpg', | |
'http://ivayloyovchev.com/pulsepro/data/img/gallery/wedding/IMG_3312.jpg', | |
'http://ivayloyovchev.com/pulsepro/data/img/gallery/lifestyle-fashion/IMG_0050_.jpg', | |
'http://ivayloyovchev.com/pulsepro/data/img/gallery/lifestyle-fashion/BROKEN.jpg' | |
]; | |
// queue load handlers | |
function onDone(){ console.log('loaded all images'); } | |
function onFail(){ console.log('failed to load all images'); } | |
function onAlways(){ console.log("completed all images - some may be broken"); } | |
// 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, onAlways, onFail, onLoad, onError); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment