0

I have a basic image element on my page. I am capturing it's load event to log a message to my console.

$("#myImg").on('load', function() {
    console.log("Loaded");
});

The above code works perfectly fine, unless the image that is being loaded already exists within the users cache, in that case the message is not loaded at all.

Is there an event such as loaded to check if the image is already loaded?

Fizzix
  • 20,849
  • 34
  • 100
  • 160

2 Answers2

15

Check imageObj.complete before load event. complete is image object property.

HTMLImageElement.complete : Returns a Boolean that is true if the browser has finished fetching the image, whether successful or not. It also shows true, if the image has no src value.

var elem = $("#myImg");

if (!elem.prop('complete')) {
  console.log("Waiting to be loaded!");
  elem.on('load', function() {
    console.log("Loaded!");
    console.log(this.complete);
  });
} else {
  console.log("Already loaded!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img src='http://www.wired.com/wp-content/uploads/2015/09/google-logo.jpg' id='myImg'>
Rayon
  • 34,175
  • 4
  • 40
  • 65
0

You can append a random number as a version to the image. So every time it will load the image and not take it from cache on page reload.

var randNum = Math.random();
var imageSource= "../include/images/image.png?v="+randNum ;

Assign imageSource to the src attribute of your img tag.

abhiagNitk
  • 947
  • 9
  • 19