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

后端 未结 3 1331
余生分开走
余生分开走 2020-12-09 23:13

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 retr

相关标签:
3条回答
  • 2020-12-09 23:49

    Use window.stop to stop download

     if(window.stop !== undefined)
     {
        window.stop();
     }
     else if(document.execCommand !== undefined)
     {
     document.execCommand("Stop", false);
     }
    

    To change image source

     var img = document.getElementBYId("yourImageID");
     img.setAttribute("src","newSource.gif");
    
    0 讨论(0)
  • 2020-12-09 23:55

    You can use this code to load an image and, if not successfully loaded within 1 second (whether the failure is via onerror, onabort or from the time elapsing), switch to load an alternate image.

    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");
    
    0 讨论(0)
  • 2020-12-10 00:05

    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
    );
    
    0 讨论(0)
提交回复
热议问题