img重新加载并避免404 1像素图像返回

时间:2013-09-22 20:37:35

标签: javascript

我正在上传图片,处理部分需要时间,我只能通过它来检测客户端。所以我使用这个脚本

function: loadImage(src, callback){
    var i = new Image(),        
    that = this;
    i.onload = function(){
        //we might get a 1 pixel image back from the webserver in case of a 404, which might also get cached
        if(i.width <= 1){
            setTimeout(function(){
                var newSrc = (src.indexOf('?') > -1? src.substring(0,src.indexOf('?')) : src) + '?rnd=' + new Date().getMilliseconds();
                i.src=null;
                i.src = newSrc;
            },5000);
            return;
        }
        callback(i);
    };
    //sometimes images are not there yet because they are being processed. So we have to rerun the function every x seconds
    i.onerror = setTimeout(function(){
        var newSrc = (src.indexOf('?') > -1? src.substring(0,src.indexOf('?')) : src) + '?rnd=' + new Date().getMilliseconds();
        i.src=null;
        i.src = newSrc;
    },5000);

    i.src = src;
}

因此,当图像返回404时,许多网络服务器返回1像素图像,以防止丑陋的图像碎片,在这种情况下,我想再做一轮,直到我得到其他东西。

然而,当调用onload处理程序并重置src时,它不会导致新的图像加载。对此有何建议?

0 个答案:

没有答案