Home > Web Front-end > JS Tutorial > How to Set Timeouts for Asynchronous Image Loading with jQuery?

How to Set Timeouts for Asynchronous Image Loading with jQuery?

Linda Hamilton
Release: 2024-11-12 07:31:01
Original
378 people have browsed it

How to Set Timeouts for Asynchronous Image Loading with jQuery?

Asynchronous Image Loading with jQuery

It's essential to load images asynchronously to avoid blocking the page's rendering and ensure a smooth user experience. While $.ajax() is a valuable tool for asynchronous operations, it's not explicitly designed for image loading.

Using jQuery's .load Method

jQuery provides a convenient .load() method that can load external content, including images. However, setting a timeout for image loading is not straightforward using .load().

Alternative Using Native Image Element

An alternative approach is to create a new image element directly and set its source attribute. This allows for more flexibility in handling image loading.

Setting a Timeout

To set a timeout for asynchronous image loading, follow these steps:

  1. Create the image element:

    var img = $("<img />");
    Copy after login
  2. Set the source attribute:

    img.attr('src', 'http://somedomain.com/image.jpg');
    Copy after login
  3. Handle the load event:

    img.on('load', function() {
        // Checks if the image has loaded successfully
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            // Image failed to load
            alert('broken image!');
        } else {
            // Image loaded successfully
            $("#something").append(img);
        }
    });
    Copy after login

When the image is loaded successfully, you can append it to the desired location in your HTML. If the image fails to load (e.g., 404), you can handle the error as you deem fit.

The above is the detailed content of How to Set Timeouts for Asynchronous Image Loading with 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