Detect image load

半城伤御伤魂 提交于 2019-11-26 04:18:34

问题


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


回答1:


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();
});



回答2:


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;



回答3:


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.




回答4:


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
     });
}



回答5:


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...
   });
}) ;



回答6:


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.



来源:https://stackoverflow.com/questions/3537469/detect-image-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!