Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - How to cancel an image load after a period of time?

I need to be able to cancel an image load after a set period of time, and it needs to subsequently call the onError action.

What it will do:

Attempt to retrieve the resource. src="https://www.site.com/cgi-bin/pullimg.cgi?user=+encodeURI(document.cookie) , which pulls a user-specific resource. The cookies are stored in a protected folder.

If it can't in 1 second (1000 ms), then execute onError.

onError changes the images src attribute, then reloads the img. (Changes to different uri, like mirror.site.com/err.png)

Also, it can be a javascript function (newImage).

Sorry for not supplying existing code; I can code in multiple langs though.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...