Dynamically inserting an image with JavaScript does not work on images that 302 redirect

Posted by Samuel Clay on Stack Overflow See other posts from Stack Overflow or by Samuel Clay
Published on 2010-04-16T03:07:09Z Indexed on 2010/04/16 3:13 UTC
Read the original article Hit count: 434

Filed under:
|
|

I am dynamically inserting an image into an HTML document using jQuery. Here is the code:

var image_url = "http://www.kottke.org/plus/misc/images/castro-pitching.jpg";
var $image = $('<img src="'+image_url+'" width="50" height="50" />');
$('body').prepend($image);

Notice that the image http://www.kottke.org/plus/misc/images/castro-pitching.jpg is actually a 302 redirect to http://kottkegae.appspot.com/images/castro-pitching.jpg.

If you were to go to the original image in your browser, it works fine. If you were to load an HTML page with that image in an img tag, it would load fine.

However, if you were to insert it dynamically using jQuery (or JavaScript, for that matter), the browser will not show the 302'ed image.

If you show the redirected image, it would work fine.

var image_url = "http://kottkegae.appspot.com/images/castro-pitching.jpg";
var $image2 = $('<img src="'+image_url+'" width="50" height="50" />');
$('body').prepend($image2);

That's crazy, right? What gives and how can I force the image to load when inserted dynamically?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JavaScript