jquery预加载图像

时间:2009-10-15 22:27:16

标签: jquery image load preload

好的,所以我有这个“slideshow.html”只包含一堆图片和“index.html”。

的index.html

<a href="">click</a>
<ul></ul>

slideshow.html

<li><img src="1.jpg" alt="" /></li>
<li><img src="2.jpg" alt="" /></li>
<li><img src="3.jpg" alt="" /></li>

我的脚本是这样的;

$(document).ready(function(){
            $('a').click(function(){
            $('ul').append('<li id="preloader"><img src="preLoader.gif" /></li>');
                   $('ul').load('slideshow.html',function(){
                           $('#preloader').remove();
                   });
            });
});

所以我想点击以附加preloader.gif并调用load方法,并在图像形成后加载slideshow.html以删除动画。使用我的脚本它赢了; t做的事情,页面加载但动画在图像完全加载之前被删除:(谢谢

2 个答案:

答案 0 :(得分:2)

$(document).ready(function(){
    //anchor click
$('a').click(function(){
    //empty the div
    $('div').empty();
            //perform ajax request
    $('div').load('toLoad.html',function(){
                  //hides all loaded images
        $('div.imageHolder img').hide();
                  //applies preloader for each image loaded
        $('div.imageHolder img').each(function(){
            //creates new image object
            var img = new Image();
                            //the current image src is stored in sursa variable
            var sursa = $(this).attr('src');
                            //the current image parent is stored in parent var 
            var parent = $(this).parent();
                            //the load animation is appended to current image parent 
            parent.append('<img src="blueLoader.gif" alt="loader" />');
           //loading image css settings
            $('img[alt="loader"]').css({'display':'block','margin':'10px auto'});
                           //this is the key
            $(img).load(function(){
                            //after image is loaded
                parent.append($(this));
                $(this).hide().fadeIn(500).css({'width':'200px','height':'80px'});
                $(this).siblings().remove();
            }).attr('src',sursa);


        });

    });
    return false;
}); 
   });

答案 1 :(得分:0)

预加载图像与此不同。在jQuery中,可以这样做(未经测试):

$('<ul><li id="image1"><img id="throbber1" scr="preLoader.gif" /></li></ul>').appendTo('body');
var $img = $(new Image()).attr('src', '1.jpg').appendTo('ul li#image1');
$img.load(function() {
    $('#throbber1').hide();
});