Reputation: 7113
I have a image loader function, that calls a function when all images are loaded, regardless how many I load. But currently it fails when a image src file name is not valid, because onload is not called.
How can I throw an error message, if an image is not loaded?
loadImage: function(image, id, fn) {
var bgImg = new Image(),
self = this;
// counting images currently loaded
this._loadingImages++;
// set image source and onload callback
bgImg.src = image;
bgImg.onload = function() {
fn(image, id);
self._loadingImages--;
if( self._loadingImages === 0 ) self.imagesLoaded();
}
},
Upvotes: 0
Views: 768
Reputation: 7113
Thanks to t.niese, this is my solution:
loadImage: function(image, id, fn) {
var bgImg = new Image(),
self = this;
// counting images currently loaded
this._loadingImages++;
// set error and onload callback and then image source
bgImg.onerror = function() {
throw new Error( "ERROR" );
};
bgImg.onload = function() {
fn(image, id);
self._loadingImages--;
if( self._loadingImages === 0 ) self.imagesLoaded();
}
bgImg.src = image;
},
Upvotes: 0
Reputation: 5660
loadImage: function (image, id, fn) {
var bgImg = new Image(),
self = this;
// counting images currently loaded
this._loadingImages++;
// set image source and onload callback
bgImg.src = image;
bgImg.onerror = function () {
// your error code
}
bgImg.onload = function () {
fn(image, id);
self._loadingImages--;
if (self._loadingImages === 0) {
self.imagesLoaded();
}
}
};
This should work.
Upvotes: 2
Reputation: 2910
This Thread can help you: Check if an image is loaded (no errors) in JavaScript
I guess with jQuery you can achieve this such the answer on the link that I've copied below:
$("<img/>")
.load(function() { console.log("image loaded correctly"); })
.error(function() { console.log("error loading image"); })
.attr("src", $(originalImage).attr("src"))
;
Upvotes: 1