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?
use .load to load your image. to test if you get an error ( let's say 404 ) you can do the following:
careful - .error() event will not trigger when the src attribute is empty for an image.
This works too ..
You can use a Deferred objects for ASYNC loading.
Please pay attention: image.onload must be before image.src to prevent problems with cache.
Should be better than ajax because if its a gallery and you are looping through a list of pics, if the image is already in cache, it wont send another request to server. It will request in the case of jQuery/ajax and return a HTTP 304 (Not modified) and then use original image from cache if its already there. The above method reduces an empty request to server after the first loop of images in the gallery.