I'm loading (large) images dynamically to draw into a html5 canvas, something like this:
var t = new Image();
t.onload = ...
t.src = 'http://myurl';
But every once in a while would like to cancel the image request completely.
The only way I came up with is setting src to ''. i.e.
t.src = ''
This works in many browsers, but it seems that only Firefox actually cancels the http request for the image.
I tested this with Fiddler2 by disabling caching and enabling "emulate modem speed". Then running a fiddle to test canceling a image request. (I'd love to hear other ideas on how to test this)
I know there are ways to cancel all requests (as in this question), but I'd like to only cancel one.
Any ideas on other ways (especially on mobile browsers) to do this?
This is the only way that I managed to get it to work in all modern browsers (Chrome, Safari, Mobile-Safari, Firefox, and IE9).
iframeimage tag to the body in the iframeimg.onload completes, you can use that image dom element to draw to an html5 canvas with drawImage()stop() on the iframe's contentWindow (or execCommand("stop", false) on contentDocument in IE).I created a class for this, and put the coffeescript code (and it's 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.
You can try window.stop() to stop all requests, but not individual ones. In IE, it's not window.stop() it's document.execCommand("Stop", false).
If you've got other stuff going on request-wise, then doing this will interfere with it. (You would follow-up with a re-request for resources you still want, but that is too much like hard work).
So if you wanted to stop a single request for a large image, what you could do is load the image into a document within a hidden IFRAME. The onload event of the IFRAME can be used to load the image into the main document, by which time it ought to be cached (presuming you have the caching directives configured to do so).
If the image is taking too long, then you can access the IFRAME's contentWindow and issue a stop command to that.
You need to have as many IFRAME elements as there are images that can be requested simultaneously.
I doubt there's a cross-browser way to make this happen without hacks. One suggestion is to make an AJAX request to a server-side script which returns a Base64 encoded version of the image which you can then set as the src attribute. Then you can cancel this request if you decide to cancel loading the image. This could be difficult if you want to show the image progressively however.