Home >Web Front-end >JS Tutorial >How can I asynchronously load external images using jQuery?

How can I asynchronously load external images using jQuery?

Susan Sarandon
Susan SarandonOriginal
2024-11-11 05:23:02646browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn