开发者

Remove background image on image load

开发者 https://www.devze.com 2023-01-05 16:33 出处:网络
I\'m loading image tags via AJAX and inserting them with the conventional .html(content) function 开发者_如何学编程in jQuery alongside a bunch of other HTML. However, this question still applies if yo

I'm loading image tags via AJAX and inserting them with the conventional .html(content) function 开发者_如何学编程in jQuery alongside a bunch of other HTML. However, this question still applies if you're loading a page from scratch. Now, I have a background image placeholder to be put there while the image loads. I want this background image to go away when the image loads.

Problem:

If I attach a conventional .load(function) event listener, I am concerned that the image might load before the hook is applied (putting the hook in a small JS <script> right after the image instead of in a $(function(){}) block might help a bit). I have yet to encounter such behaviour, but I know of nothing in the specification that prevents this from happening (since the image tag ought to be fully parsed before the hook is applied).

My current solution. Put the command in an inline onload= property within the image tag.

Is there a better way?


Up until a week or so ago I would have been lost too. Thankfully this answer to another question will help you out:

Basically put this in $():

$(function(){ 
   var img = $("#idofimage").load(function () { 
      /* your magic to swap out placeholder */ 
   });

   if (img[0].complete) {
     // Trigger the load handler if the image
     // is already loaded
     img.trigger('load');
   }

});


You don't need jQuery for this, you can do it with CSS.

.my-img-loader-class { background:url('placeholder-or-progress'); }

Or if you don't want to change your HTML:

#container img { background:url('placeholder-or-progress'); }

To show placeholders while images are loading in a specific div.

The way it works is the image element will show the placeholder image as its background, and when the src loads it will appear above the placeholder, so as to replace it nicely.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号