简体   繁体   中英

JScript: How can I throw an error message when image is not loaded?

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(); 
   }
},
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.

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"))
;

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;   
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM