图像失败需要多长时间?

时间:2013-08-02 17:51:35

标签: javascript

我从互联网上加载图片:

img.src = 'some_path'

我注意到如果网络速度慢,有些图片需要很长时间才能加载,有些图像需要很长时间才能加载然后失败。

有时候,域名会崩溃。如果服务器关闭,这很有效,因为错误会很快抛出,我可以捕获错误并相应地更改src

但是,对于速度慢但失败的页面 - 我看到浏览器显示某种空白框,表示最终错误输出之前的10秒或更长时间。

似乎太长了。我会说给网站大约4秒钟然后如果它没有响应则抛出错误。

无论如何要调整这个吗?

客户端在抛出错误之前等待的时间?

让这种空白blox盯着用户10秒或更长时间看起来很草率。

目前在FireFox中。

3 个答案:

答案 0 :(得分:4)

我知道在脚本中设置超时以获取内容的唯一方法是使用 XMLHttpRequest ,因此您可以通过ajax加载图像,例如;

function getImage(src, callback, maxTime) {
    var x = new XMLHttpRequest();
    if (maxTime) x.timeout = maxTime;
    x.onload = function () {
        var img = new Image();
        img.src = window.URL.createObjectURL(this.response);
        callback(img);
    };
    x.onerror = function () {
        callback(null);
    };
    x.open('GET', src, true);
    x.responseType = 'blob'; // save having to re-create blob
    x.send(null);
}
getImage(
    'some_path',     // get image at "some_path"
    function (img) { // then
        if (!img) alert('failed!');          // whatever if didnt work
        else document.body.appendChild(img); // whatever if did work
    },
    4000             // maximum wait is 4 seconds
);

此方法的缺点是浏览器向后兼容性,如果服务器返回某些内容但它不是图像

答案 1 :(得分:2)

试试这个:

var img = document.getElementById("myImg")
img.src = 'https://atmire.com/dspace-labs3/bitstream/handle/123456789/7618/earth-map-huge.jpg?sequence=1'; //very big image, takes like 7 seconds to  load
window.setTimeout(function()
{
    if(!IsImageOk(img))
        img.src = "http://www.google.com/images/srpr/logo4w.png";
},4000);

function IsImageOk(img) {
    // During the onload event, IE correctly identifies any images that
    // weren’t downloaded as not complete. Others should too. Gecko-based
    // browsers act like NS4 in that they report this incorrectly.
    if (!img.complete) {
        return false;
    }

    // However, they do have two very useful properties: naturalWidth and
    // naturalHeight. These give the true size of the image. If it failed
    // to load, either of these should be zero.

    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
        return false;
    }

    // No other way of checking: assume it’s ok.
    return true;
}

jsFiddle:http://jsfiddle.net/hescano/mLhdv/

使用Check if an image is loaded (no errors) in JavaScript

中的代码

请注意,第一次代码运行正常,但之后图像将被缓存,并且可能加载速度更快。

答案 2 :(得分:2)

交叉/向后兼容

function loadImage(src, complete, timeout) {
    var img = document.createElement("img");
    img.src = src;
    setTimeout(function() {
        complete(img.complete && img.naturalWidth !== 0 ? img : false);
    }, timeout || 5000);
}

loadImage("path/to/image.png", function(img) {
    if(img) {
        //TODO ON SUCCESS
    } else {
        //TODO ON FAILURE
    }
}, 4000);