Skip to content Skip to sidebar Skip to footer

Load Image If Found, Else Load Another Image

what I need to do is simple to say but (for me) hard to do: using javascript, given an image name, ie 'image01.jpg', I need to check if this image exists in a certain folder or pat

Solution 1:

Use the onerror callback :

var img = newImage();
img.onerror = function(){
   img = newImage(); // clean the error (depends on the browser)
   img.onerror = function(){
       console.log('not found at all !');
   };
   img.src = path2+'/'+imageToFind;
};
img.src = path1+'/'+imageToFind;

Solution 2:

You can pretty much rely on native onload and onerror event handlers which fire for Image nodes. So it could look like

var images = ['users/john/images/image01.jpg','users/mike/img/image01.jpg','some/more/path/image01.jpg'];

(function_load( img ) {
    var loadImage = newImage();

    loadImage.onerror = function() {
        // image could not get loaded, try next one in list_load( images.shift() );
    };
    loadImage.onload = function() {
        // this image was loaded successfully, do something with it
    };

    loadImage.src = img;
}( images.shift() ));

This code probably does a little more than you actually asked for. You can basically but as much image paths as you wish into that array, the script will search the list until it could load one image successfully.

Solution 3:

try something like

objImg = new Image();
objImg.src = 'photo.gif';

if(!objImg.complete)
 { 
      img.src = path2+'/'+imageToFind; //load other image
  }else{
     img.src = path1+'/'+imageToFind;
  }

Solution 4:

I think you need to ask yourself: why don't I know whether the images exist?

I feel like you should not have this problem, or want to solve it in this way.

Post a Comment for "Load Image If Found, Else Load Another Image"