开发者

jQuery - Complete loading animation on each individual image?

I am currently using jQuery to manipulate a loading placeholder image that covers loading thumbnails on my website. Basically, the script waits for the page to finish loading, and then hides the loading 开发者_JAVA技巧animation. You can see the effect at my site, here.

On a page that has many images to load, however, it can take quite some time before the thumbnails appear.

I had considered using some sort of lazy-loading technique, but I think it might be simpler to just switch the trigger for the loading animation hiding from the completion of the loading of the entire page to just the completion of loading of each particular image. I have give this a shot with the following script:

<script type="text/javascript"> $('div[id^="photo"]').load(function() { $(this+"_loading").fadeOut('slow'); }); </script>

It doesn't seem to be working, though. Can anyone help me out?

Thanks!


From the jQuery docs @ http://api.jquery.com/load-event/:

"This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object."

Bind you load event to the image itself, and find the corresponding loading text from the callback function.

$(function(){
   $('div[id^="photo"] img').load(function(){
      $(this).closest('div').find('.loading').fadeOut("slow");
   });

   $('div[id^="photo"] img').each(function(){
      var src = $(this).attr('src');
      $(this).attr('src','#');
      $(this).attr('src',src);
   });
});

This code above allows minor rearrangement of your markup.

You also have to make sure to bind the load event in your ready function, after your DOM is ready and jQuery has loaded. Inline script elements are executed as soon as they're parsed.

Edit: As mentioned in the jQuery docs above, there are several caveats that make this unreliable in certain browsers, sometimes this event doesn't fire for images already in the cache, and on webkit it doesn't fire if you change the image src to the same value as before. There is an interesting point in this forum thread about it: http://forum.jquery.com/topic/image-load-event-some-progress

I edited the code above to add some workarounds, although it's not guaranteed to work.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜