How to cancel an image from loading How to cancel an image from loading javascript javascript

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.


Although I can't find the bug report now, I believe this is a long-standing logged WebKit bug. Firefox (and IE I think) have more sane behavior. I'm going back a bit in my brain, but if I recall on those browsers, resetting the img.src will in fact cancel outstanding downloads. I am positive that Firefox does this when a download is "waiting in line" for a chance at an open HTTP connection, and I seem to recall that it will actually force close connections sometimes.

I've never found a way to coax WebKit based browsers into cancelling an img download in progress, whether it is just queued or already actively downloading.

This really sucks if you're making something like a mapping client and need more fine grained control over images.


Setting the .src property to an empty string should cancel the load:

//load image from urlvar img = new Image();img.src = 'http://somedomain.com/image.jpg';......//cancel loadimg.src = '';