Can I check whether an image has already been loaded earlier using Javascript or jQuery?

StackOverflow https://stackoverflow.com/questions/22271639

سؤال

Consider the following image appended to the document :

<img id="someimage" src="http://www.someimage.jpg">

None of the following will work if the image has already been loaded by the time these functions are called :

document.getElementById('someimage').onload = function ()
{
  console.log('image just loaded');
};

nor

$("#someimage").load(function ()
{
  console.log('image just loaded');
});

Is there a way around that ? i.e. a function that will not wait for the image to load but will check whether the image has already been loaded earlier?

Thanks

هل كانت مفيدة؟

المحلول

Check the complete property of DOM node:

document.getElementById('someimage').complete;

BTW, this is how you should handle it:

$("#someimage").one('load', function ()
{
  console.log('image just loaded');
}).each(function(){
    if(this.complete) $(this).trigger('load');
});

نصائح أخرى

YOu can use the src property for this.

var image = document.getElementById('someimage');
if(image != null){
    if(image.src  == "http://www.someimage.jpg"){
       console.log("your image is loaded");
   }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top