我知道为在脚本中获取内容设置超时的唯一方法是使用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
);
这种方法的缺点是浏览器向后兼容,如果服务器返回一些东西但它不是图像