Javascript: Cancel/Stop Image Requests

Javascript: Cancel/Stop Image Requests

I had the exact same issue, when users 'paged' quickly through (ajax) search results the browser was still trying to download profile images for every page not just the current one. This code worked for me, called on the paging event just before the new search was run:

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

Essentially it's like clicking the "Stop" button on the browser.

Tested in IE, FireFox, Chrome, Opera and Safari

Cancel single image request in html5 browsers

This is the only way that I managed to get it to work in all modern browsers (Chrome, Safari, Mobile-Safari, Firefox, and IE9).

  • Load an empty and hidden iframe
  • append an image tag to the body in the iframe
  • when the img.onload completes, you can use that image dom element to draw to an html5 canvas with drawImage()
  • if you want to cancel the load, issue a stop() on the iframe's contentWindow (or execCommand("stop", false) on contentDocument in IE).
  • after you cancel a image load, you can reuse the iframe to load more images.

I created a class for this, and put the coffeescript code (and its compiled javascript) on github:
Cancelable Html5 Image Loader

If you want to play with it, I also created a jsfiddle to test it out. Remember to start Fiddler2 (or something like it) to see that the actual network request is really being canceled.

How do I abort image img load requests without using window.stop()

What you are trying to do is the wrong approach, as mentioned by nrabinowitz. You can't just "cancel" the loading process of an image (setting the src attribute to an empty string is not a good idea). In fact, even if you could, doing so would only make things worst, as your server would continually send data that would get cancelled, increasing it's load factor and slow it down. Also, consider this:

  1. if your user scroll frenetically up and down the page, he/she will expect some loading delays.
  2. having a timeout delay (ex: 200 ms) before starting to load a portion of the page is pretty acceptable, and how many times will one stop and jump after 200 ms interval on your page? Even it it happens, it comes back to point 1
  3. how big are your images? Even a slow server can serve about a few tens of 3Kb thunbnails per second. If your site has bigger images, consider using low and hi resolution images with some components like lightBox

Often, computer problems are simply design problems.

** EDIT **

Here's an idea :

  1. your page should display DIV containers with the width and height of the expected image size (use CSS to style). Inside of each DIV, add an link. For example :

    <div class="img-wrapper thumbnail">
    <a href="http://www.domain.com/path/to/image">Loading...</a>
    </div>
  2. Add this Javascript (untested, the idea is self describing)

    $(function() {

    var imgStack;
    var loadTimeout;

    $(window).scroll(function() {
    imgStack = null;
    if (loadTimeout) clearTimeout(loadTimeout);

    loadTimeout = setTimeout(function() {

    // get all links visible in the view port
    // should be an array or jQuery object
    imgStack = ...

    loadNextImage();
    }, 200); // 200 ms delay
    });

    function loadNextImage() {
    if (imgStack && imgStack.length) {
    var nextLink = $(imgStack.pop()); // get next image element

    $('<img />').attr('src', nextLink.attr('href'))
    .appendTo(nextLink.parent())
    .load(function() {
    loadNextImage();
    });

    // remove link from container (so we don't precess it twice)
    nextLink.remove();
    }
    };

    });

How to cancel an image from loading

Quick answer

Setting the src attribute of the img tag to the empty string will interrupt the current download, even on Chrome.

Details

Nowadays most of browsers implemented that out-of-standard mechanism thought in the old answer to programmatically abort the connection. This is not achieved through a protocol request, but with a client-side in-memory operation. Keep in mind that is not a standard behaviour, but most of vendors courtesy. That is, it could not work on every browser.

I've prepared a jsfiddle showing this mechanism in action (keep an eye at the network panel of the inspector).


Old answer (2011)

Your browser asks for that image with a specific HTTP GET request, as specified in HTTP protocol. Once it asks for it, the http server starts the transfer.

So, it is between the browser (as http client) and the http server.

Since http protocol does not takes into account the option to abort a transfer, the browser should implement a out-of-standard mechanism to programmatically abort the connection. But since this is not specified in any standard, i think you won't find any way to do that with javascript or any client side code.

javascript: cancel all kinds of requests

window.stop() should cancel any pending image or script requests.

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

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


Related Topics



Leave a reply



Submit