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?