Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return binary image data from an abortable AJAX request and set the result to the src of an HTML/DOM image?

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?

like image 709
Michael Avatar asked Feb 25 '10 01:02

Michael


2 Answers

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.

like image 185
bobince Avatar answered Oct 13 '22 00:10

bobince


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.

like image 28
Michael Pilat Avatar answered Oct 13 '22 00:10

Michael Pilat