Home >Web Front-end >JS Tutorial >How can I asynchronously load external images using jQuery?
Asynchronous Image Loading with jQuery
Question: Is it possible to asynchronously load external images using jQuery? If so, how?
Response:
Yes, it is possible to asynchronously load images using jQuery. Here are two methods you can use:
Method 1: Using an XHR Request
$.ajax({ url: "http://somedomain.com/image.jpg", timeout: 5000, success: function() { // Handle success }, error: function(r, x) { // Handle error } });
However, this method may not always return an error for unavailable images.
Method 2: Using the load Method
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); } });
This method allows you to handle 404 errors by checking if the image is broken or not.
The above is the detailed content of How can I asynchronously load external images using jQuery?. For more information, please follow other related articles on the PHP Chinese website!