[英]How long does it take an image to fail -?
我从互联网上加载图像:
img.src = 'some_path'
我注意到如果网络速度慢,有些图像需要很长时间才能加载,有些图像需要很长时间才能加载然后失败。
有时候,域名一起倒下了。 如果服务器关闭,这很好用,因为错误会很快抛出,我可以捕获错误并相应地更改src
。
但是,对于慢速然后失败的页面 - 我看到浏览器显示某种空白框,看起来像10秒或更长时间,最后出错。
这似乎太长了。 我会说给网站大约4秒钟然后如果它没有响应则抛出错误。
反正有调整吗?
客户端在抛出错误之前等待的时间量?
让这种空白blox盯着用户10秒或更长时间看起来很邋。
目前在FireFox中。
我知道在脚本中设置超时以获取内容的唯一方法是使用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
);
此方法的缺点是浏览器向后兼容性,如果服务器返回某些内容但它不是图像
试试这个:
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/
使用代码来检查JavaScript中是否加载了图像(没有错误)
请注意,第一次代码运行正常,但之后图像将被缓存,并且可能加载更快。
交叉/向后兼容
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.