Home >Web Front-end >JS Tutorial >How to Ensure an Onload Event is Triggered for an Image, Even if It\'s Cached?

How to Ensure an Onload Event is Triggered for an Image, Even if It\'s Cached?

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 05:49:29979browse

How to Ensure an Onload Event is Triggered for an Image, Even if It's Cached?

Image onload Event and Browser Cache

You want to trigger an alert box when an image has been loaded, regardless of whether the image has been cached or not. The solution is to set the onload property before the src.

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

This will work on the latest Firefox and Chrome releases. You can also use the answer in another post, which is adapted for a single dynamically generated image:

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

This will also work on the latest Firefox and Chrome releases.

The above is the detailed content of How to Ensure an Onload Event is Triggered for an Image, Even if It\'s 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