Asynchronously load images with jQuery

Arief picture Arief · Nov 26, 2010 · Viewed 255.5k times · Source

I want to load external images on my page asynchronously using jQuery and I have tried the following:

$.ajax({ 
   url: "http://somedomain.com/image.jpg", 
   timeout:5000,
   success: function() {

   },
   error: function(r,x) {

   }
});

But it always returns error, is it even possible to load image like this?

I tried to use .load method and it works but I have no idea how I can set timeout if the image is not available (404). How can I do this?

Answer

karim79 picture karim79 · Nov 26, 2010

No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:

var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
    .on('load', function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            alert('broken image!');
        } else {
            $("#something").append(img);
        }
    });