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
Release: 2024-11-11 05:23:02
Original
643 people have browsed it

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
    }
});
Copy after login

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);
        }
    });
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template