我需要能够在一段时间后取消图像加载,并且需要随后调用onError操作.
它会做什么:
onError更改图像src属性,然后重新加载img.(对不同uri的更改,如mirror.site.com/err.png)
此外,它可以是一个javascript函数(newImage).
很抱歉没有提供现有代码; 我可以编写多个langs代码.
试试这个:
var image = new Image();
image.src = "https://www.site.com/cgi-bin/pullimg.cgi?user=" + encodeURI( document.cookie );
setTimeout
(
function()
{
if ( !image.complete || !image.naturalWidth )
{
image.src = "http://mirror.site.com/err.png";
}
},
1000
);
Run Code Online (Sandbox Code Playgroud)
您可以使用此代码加载图像,如果在 1 秒内未成功加载(无论失败是由于 onerror、onabort 还是由于时间流逝),请切换到加载备用图像。
function loadImage(url, altUrl) {
var timer;
function clearTimer() {
if (timer) {
clearTimeout(timer);
timer = null;
}
}
function handleFail() {
// kill previous error handlers
this.onload = this.onabort = this.onerror = function() {};
// stop existing timer
clearTimer();
// switch to alternate url
if (this.src === url) {
this.src = altUrl;
}
}
var img = new Image();
img.onerror = img.onabort = handleFail;
img.onload = function() {
clearTimer();
};
img.src = url;
timer = setTimeout(function(theImg) {
return function() {
handleFail.call(theImg);
};
}(img), 1000);
return(img);
}
// then you call it like this
loadImage("https://www.example.com/cgi-bin/pullimg.cgi?user=" + encodeURI(document.cookie), "http://mirror.site.com/err.png");
Run Code Online (Sandbox Code Playgroud)