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
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;
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With