开发者

jquery how to call an image preloader recursively

I have a very simple jQuery preloader that works ok (i believe the code is correct but please go ahead and check it out)...

What i'm trying to do is, if the image fails to download, then try another variation of the image until you find one.... there's only upto 4 variations that is represented by a number inside the path.

Let me explain:

An image path could be as following

.../images/800px/image1.jpg

if that one fails, then try

.../images/350px/image1.jpg

if that one fails, then try

.../images/100px/image1.jpg

if that one fails, then try

.../images/50px/image1.jpg

if that one fails, then try

.../images/30px/image1.jpg

if you notice, the diference in all of those variations, is the number inside the path... that is 800, 350, 100, 50, 30

Now, in the function load_img (below) i was thinking of using the .error atribute to call the function recursively until it finds an image..

IS this the best approach? any hints or best practices on how to achieve this?

Thanks in advance

Marco

Here's a sample of the code

<div id="zoom-artwork"></div>

<ul class="nav-zoom-artwork">
   <li><a href=".../images/800px/image1.jpg">image doesn't exist...</a></li>
   <li><a href=".../images/800px/image2.jpg">image 2</a></li>
   <li><a href=".../images/800px/image3.jpg">image 3</a></li>
</ul>

...

$('#nav-zoom-artwork a').click(function(e) {
   var src = $(this).attr('href');
   var alt = $(this).children('img').attr('alt');   

   load_img(src, alt);

   e.preventDefault();
});


// ZOOM artwork
function load_img(src, alt) {
   var img = new Image();

   $(img).load(function() {
      // se开发者_如何学JAVAt the image hidden by default
      $(this).hide(); 

      // remove the loading class, then insert the image
      $('#zoom-artwork').removeClass('loading').html(this);

      // fade in the image to create a nice effect
      $(this).fadeIn(400);
   })
   .error(function() {
      alert('try another size... call the function recursively with another path...');
   })
   .attr({
      src:src,
      alt:alt
   });
}


turn out to be simpler then i previously thought.... just added this piece of code on .error function and voila!....

...  
})
.error(function() {
        //try other sources
        if (other_src != null && other_src.length) {
            //alert('found another source, loaded!');
            load_img(other_src, alt, el, null);

        } else {
            alert('no more sources...');
        }
})
...

i just need to pass a third argument to the function

function load_img(src, alt, other_src) {    
...
}

and call it

load_img(src, alt, '#zoom-cover', a_str[0]);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜