Pergunta

Is it possible to detect once an image has been loaded with jQuery?

Foi útil?

Solução

You can use the .load() event handler, like this:

$("#myImg").load(function() {
  alert('I loaded!');
}).attr('src', 'myImage.jpg');

Be sure to attach it before setting the source, or the event may have fired before you attached a handler to listen for it (e.g. loading from cache).

If that's not doable (setting the src after binding), be sure to check if it's loaded and fire it yourself, like this:

$("#myImg").load(function() {
  alert('I loaded!');
}).each(function() {
  if(this.complete) $(this).load();
});

Outras dicas

It's just as simple to use plain Javascript:

  // Create new image
var img = new Image();

  // Create var for image source
var imageSrc = "http://example.com/blah.jpg";

  // define what happens once the image is loaded.
img.onload = function() {
    // Stuff to do after image load ( jQuery and all that )
    // Within here you can make use of src=imageSrc, 
    // knowing that it's been loaded.
};

  // Attach the source last. 
  // The onload function will now trigger once it's loaded.
img.src = imageSrc;

I've been also researching this for long time, and have found this plugin to wonderfully help with this: https://github.com/desandro/imagesloaded

It seems like an aweful lot of code, but...I found no other way for checking when an image has been loaded.

Using jQuery on('load') function is the right way to check if the image is loaded. But be aware that the on('load') function will not work if the image is already in cache.

var myImage = $('#image_id');
//check if the image is already on cache
if(myImage.prop('complete')){ 
     //codes here
}else{
     /* Call the codes/function after the image is loaded */
     myImage.on('load',function(){
          //codes here
     });
}

It's easy with jquery:

$('img').load(function(){
   //do something
});

If tried it with:

$('tag')html().promise().done(function(){ 
   //do something
}) ;

but that will not check if the picture is load. That fire done if the code is load. Otherwise you can check if code was done then fire the img load function and check if picture is really loaded. So we do a combination of both:

$('tag')html('<img src="'+pic+'" />').promise().done(function(){ 
   $('img').load(function(){
     //do something like show fadein etc...
   });
}) ;

I think this can help you a bit:

    $('img').error(function(){
        $(this).attr( src : 'no_img.png');
 })

So, if it loaded - will be shown original image. In other - will be shown image, that contains fact with crashed image or 404 HTTP Header.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top