BeNdErR
BeNdErR

Reputation: 17927

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 path (local or on the web). If the image does not exist under that folder, I need to check if the same image exists in another folder.

for example, with pseudo code

imageToFind = 'image01.jpg'
path1 = 'users/john/images'
path2 = 'users/mike/img'

if path1+'/'+imageToFind exists
    //do something
else
    if path2+'/'+imageToFind exists
        //do something
    else
        print('NOT FOUND')

what kind of approach do you suggest? I tryed to achieve this using ajax first, and then using javascript's Image() , but I failed in both these cases.

Thanks in advance for any help, best regards

Upvotes: 6

Views: 4074

Answers (4)

Denys Séguret
Denys Séguret

Reputation: 382160

Use the onerror callback :

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

Upvotes: 6

jAndy
jAndy

Reputation: 236022

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 = new Image();

    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.

Upvotes: 3

NullPoiиteя
NullPoiиteя

Reputation: 57322

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

Upvotes: 1

Halcyon
Halcyon

Reputation: 57729

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.

Upvotes: 0

Related Questions