Javascript 一个映像失败需要多长时间?
我从internet加载图像,如下所示:Javascript 一个映像失败需要多长时间?,javascript,Javascript,我从internet加载图像,如下所示: img.src = 'some_path' 我注意到,如果网络速度慢,一些图像需要很长时间才能加载,而一些图像需要很长时间才能加载,然后失败 有时,整个领域都在下滑。如果服务器关闭,这会很好地工作,因为会很快抛出错误,我可以捕获错误并相应地更改src 但是,对于速度慢然后失败的页面,我看到浏览器显示某种空白框,似乎持续了10秒或更长时间才最终出错 看起来太长了。我会说给站点4秒钟,如果没有响应,就会抛出一个错误 有没有办法调整这个 客户端在抛出错误之前
img.src = 'some_path'
我注意到,如果网络速度慢,一些图像需要很长时间才能加载,而一些图像需要很长时间才能加载,然后失败
有时,整个领域都在下滑。如果服务器关闭,这会很好地工作,因为会很快抛出错误,我可以捕获错误并相应地更改src
但是,对于速度慢然后失败的页面,我看到浏览器显示某种空白框,似乎持续了10秒或更长时间才最终出错
看起来太长了。我会说给站点4秒钟,如果没有响应,就会抛出一个错误
有没有办法调整这个
客户端在抛出错误之前等待的时间量
让这种空白斑点盯着用户看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:
使用来自的代码
请注意,第一次代码将正常运行,但之后图像将被缓存,加载速度可能会更快。交叉/向后兼容
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);
值为0(默认值)表示没有超时。
我只针对现代浏览器,但MDN表示这是实验性的,我找不到一个好的兼容性图表-logan的解决方案看起来更简单。我觉得没有必要,但对你来说,任何编辑:)这实际上是必要的,因为即使无法加载的图像也会被标记为完整。