如何在一段时间后取消图像加载?

8

我需要能够在一定时间后取消图像加载,并随后调用 onError 操作。

它将会做以下操作:

尝试检索资源。src="https://www.site.com/cgi-bin/pullimg.cgi?user=+encodeURI(document.cookie),该资源会拉取一个特定用户的资源。Cookie 存储在受保护的文件夹中。

如果在1秒钟(1000毫秒)内无法完成,则执行 onError。

onError 更改图像的 src 属性,然后重新加载 img。(更改为不同的 uri,例如 mirror.site.com/err.png)

此外,它可以是一个 JavaScript 函数(newImage)。

很抱歉没有提供现有代码;我可以使用多种语言进行编码。


你能否请发一下你的代码? - Emmanuel N
我没有任何完整的代码。 - Austin Burk
3个回答

12

试试这个:

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
);

7
您可以使用此代码来加载图像,如果在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");

谢谢!看起来它正在工作。现在我对HTML/JS也更了解了。 - Austin Burk
我认为这里缺少了一个左花括号。 - DaveWalley

0
使用 window.stop 停止下载。
 if(window.stop !== undefined)
 {
    window.stop();
 }
 else if(document.execCommand !== undefined)
 {
 document.execCommand("Stop", false);
 }

更改图像来源

 var img = document.getElementBYId("yourImageID");
 img.setAttribute("src","newSource.gif");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接