0

I have a lot of images in my folder. I use this function for each of them:

export function imageExist(url) 
    {
         var http = new XMLHttpRequest();
         http.open('HEAD', url, false);
         http.send();
         return http.status != 404;

//OR 
        var img = new Image();
        img.src = url;
        return img.height!=0;
    }

enter image description here

But all these fails appear in "networks" tab of the explorer:
Request URL: http://127.0.0.1/images/p_14047_0.jpg
Request Method: GET
Status Code: 404 Not Found

I am not sure but I guess it affects a lot the performances, somethimes I have about 150images in the page.

Here is how I use it, maybe there is a better way to find out if an image exists, if yes return it, otherwise return a default image.

export function getLogo(id) 
    {
        var img = new Image();
        var url = '/images/p_' + id + '.jpg';
        img.src = url;
        if(imageExist(url)) return url;
        var url = '/images/p_' + id + '.jpeg';
        img.src = url;
        if(imageExist(url)) return url;
        var url = '/images/p_' + id + '.png';
        img.src = url;
        if(imageExist(url)) return url;
        else return '/images/default.jpg';
    }

Thanks a lot for your help!

Maxiss
  • 986
  • 1
  • 16
  • 35
  • 1
    So your only problem is that there are 404 requests appearing in the networks tab? – Jb31 Jul 14 '19 at 14:11
  • Both of your `exists` approaches are asynchronous. Can't check height of image before it loads and can't get status of request until it completes – charlietfl Jul 14 '19 at 14:15
  • Yes cause there are like 200 requests.. I check if the image exist which each extension, and there are a lot of them. I already have onerror() Otherwise, is there anyway to find an existing image in a repository without trying to load it? – Maxiss Jul 14 '19 at 14:15
  • 1
    Sounds like you should glob the directory server side and return an array of what actually exists – charlietfl Jul 14 '19 at 14:19
  • Thanks, I guess you are right... I will try using it javascript side and if not I will swicth to server side indeed – Maxiss Jul 14 '19 at 15:02

0 Answers0