0

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(); 
   }
},
psxls
  • 6,807
  • 6
  • 30
  • 50
Michael
  • 6,823
  • 11
  • 54
  • 84
  • [`.error()`](http://api.jquery.com/error/) is this you want? – Jai Jan 10 '14 at 13:02
  • Check the answer of this question [image.onError event never fires, but image isn't valid data - need a work around](http://stackoverflow.com/a/9809055/1960455) – t.niese Jan 10 '14 at 13:03
  • Look at [error MDN](https://developer.mozilla.org/en/docs/DOM/DOM_event_reference/error) & [onerror MDN](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onerror) – Givi Jan 10 '14 at 13:03
  • @Jai It's not a jQuery object, so error() doesn't work – Michael Jan 10 '14 at 13:41

3 Answers3

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

This should work.

deW1
  • 5,562
  • 10
  • 38
  • 54
1

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"))
;
Community
  • 1
  • 1
felipekm
  • 2,820
  • 5
  • 32
  • 42
0

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;   
},
Michael
  • 6,823
  • 11
  • 54
  • 84