Skip to content Skip to sidebar Skip to footer

Load Lower Quality Image If Higher One Inst Available

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.jp

Solution 1:

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 :

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

    (functions(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

Post a Comment for "Load Lower Quality Image If Higher One Inst Available"