jQuery Deferred with a Fallback
HTML
<img data-backup-image="https://dbsweb-sit-www.dbs.com.sgfg"
data-image="https://dbsweb-sit-www.dbs.com.sgfg"
height="45" width="45" />
JavaScript
function preloadImage(image) {
var $deferred = $.Deferred();
// create a new image to attempt loading the requested image
var $img = $('<img />');
var self = this;
$img.one('load', function() {
$deferred.resolveWith(self, [$img.attr('src')]);
});
$img.one('error', function() {
$deferred.rejectWith(self, [$img.attr('src')]);
});
$deferred.fail(function() {
console.log('image failed to load: ' + $img.attr('src'));
});
$img.attr('src', image);
return $deferred.promise();
}
function loadImage($image) {
var promise = preloadImage($image.attr('data-image'));
promise.done(function(image) {
$image.attr('src', image);
});
promise.fail(function() {
promise = preloadImage($image.attr('data-backup-image'));
promise.done(function(image) {
$image.attr('src', image);
});
});
}
loadImage($('img'));