1

So I have a folder of images that look like this

- img
-- 001
--- banner_620x350.jpg
--- banner_300x130.jpg
--- banner_180x60.jpg
-- 002
--- banner_300x130.jpg
--- banner_180x60.jpg
-- 003
--- banner_180x60.jpg

My current way to load an image looks like this

<img src="img/003/banner_620x350.jpg" alt="001" onError="this.onerror=null;this.src='img/003/banner_180x60.jpg';" />

because we well always have a 180x60 image but we not always have a 600x350 or 300x130

What I would like to do is this

if 600x350 exists uses it
else if does 300x130 exists use it
else use 180x60

PS: I can't check server side.

Robert E. McIntosh
  • 5,557
  • 4
  • 26
  • 35

1 Answers1

4

Create a function that checks if the image can be loaded, if it can't, move on to the next etc. and if all of them fails, it still returns the last one in the array :

function checkSource(src) {
    var def = $.Deferred(),
        res = ['620x350', '180x60', '180x60'];

    (function s(i) {
        $('<img />', {src : (src + '_' + res[i] + '.jpg')}).on({
            load: function() {
                def.resolve(this.src);
            },
            error: function() {
                if (i != res.length-1) {
                    s(++i);
                }else{
                    def.resolve(this.src);
                }
            }
        });
    }(0));
    return def.promise();
};

You can call it like :

checkSource('banner').done(function(file) {
    $('img#banner').prop('src', file);
});

and it sets the source to whatever image could be loaded, in the order of the res array, i.e. in this order :

banner_620x350.jpg
banner_300x130.jpg
banner_180x60.jpg

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388