Home  >  Article  >  Web Front-end  >  How to Trigger an Image `onload` Event Even When the Image is Cached?

How to Trigger an Image `onload` Event Even When the Image is Cached?

Susan Sarandon
Susan SarandonOriginal
2024-10-25 05:07:02411browse

How to Trigger an Image `onload` Event Even When the Image is Cached?

Image onload Event and Browser Caching

When creating an alert box after an image loads, it's common to use the .onload event. However, if the image is already cached in the browser, the .onload event will not fire. This can present a challenge if you want to trigger an alert for all images, regardless of their cached status.

Solution

To resolve this issue, there are two proven methods:

Method 1: Set onload Property Before src

Dynamically generated images can trigger the onload event properly by setting the onload property before the src attribute:

var img = new Image();
img.onload = function () {
  alert("image is loaded");
};
img.src = "img.jpg";

Method 2: Use jQuery's 'load' Event

With jQuery, you can use the 'load' event to ensure the alert is triggered regardless of caching:

var img = new Image();
// 'load' event
$(img).on('load', function() {
  alert("image is loaded");
});
img.src = "img.jpg";

These techniques effectively handle both cached and non-cached images, allowing you to display the alert successfully in all cases.

The above is the detailed content of How to Trigger an Image `onload` Event Even When the Image is Cached?. 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