I'm writing a web application that involves a continuous cycle of creating (and removing) a fair number of images on a webpage. Each image is dynamically generated by the server.
var img = document.createElement("img");
img.src = "http://mydomain.com/myImageServer?param=blah";
In certain cases, some of these images outlive their usefulness before they've finished downloading. At that point, I remove them from the DOM.
The problem is that the browser continues to download those images even after they've been removed from the DOM. That creates a bottleneck, since I have new images waiting to be downloaded, but they have to wait for the old unneeded images to finish downloading first.
I would like to abort those unneeded image downloads. The obvious solution seems to be to request the binary image data via AJAX (since AJAX requests can be aborted), and set the img.src once the download is complete:
// Code sample uses jQuery, but jQuery is not a necessity
var img = document.createElement("img");
var xhr = $.ajax({
url: "http://mydomain.com/myImageServer?param=blah",
context: img,
success: ImageLoadedCallback
});
function ImageLoadedCallback(data)
{
this.src = data;
}
function DoSomethingElse()
{
if (condition)
xhr.abort();
}
But the problem is that this line does not work the way I had hoped:
this.src = data;
I've searched high and low. Is there no way to set an image source to binary image data sent via AJAX?
You would have to base64-encode the data
into a data:
URI to achieve that. But it wouldn't work in IE6-7, and there are limitations on how much data you can put in there, especially on IE8. It might be worth doing as an optimisation for browsers where it's supported, but I wouldn't rely on it.
Another possible approach is to use the XMLHttpRequest
to preload the image, then just discard the response and set the src
of a new Image
to point to the same address. The image should be loaded from the browser's cache. However, in the case where you're generating the images dynamically you would need to pay some attention to your caching headers to ensure the response is cachable.
Try e.g.
this.src="data:image/png;base64,XXX"
...where XXX
is your binary data, base64-encoded. Adjust the content-type if necessary. I wouldn't be optimistic about wide browser support for this, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With