我有一个图像加载器功能,在加载所有图像时调用一个函数,无论我加载多少个。但是目前它在图像src文件名无效时失败,因为没有调用onload。
如果未加载图片,如何抛出错误消息?
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();
}
},
答案 0 :(得分:2)
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();
}
}
};
这应该有用。
答案 1 :(得分:1)
此主题可以帮助您:Check if an image is loaded (no errors) in JavaScript
我想用jQuery你可以在下面复制的链接上实现这个答案:
$("<img/>")
.load(function() { console.log("image loaded correctly"); })
.error(function() { console.log("error loading image"); })
.attr("src", $(originalImage).attr("src"))
;
答案 2 :(得分:0)
感谢t.niese,这是我的解决方案:
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;
},