2009-11-04 53 views
2

有人可以帮助我理解如何从random.php页面预加载图像,因此第一次加载它时就会像应该那样淡入。目前它有一个丑陋的散装回声,因为他们不预装但一旦页面已经被运行一次,它的另一完全消失后,上...从Ajax调用预加载图像

//Loop through the images and print them to the page 
for (var i=0; i < totalBoxes; i++){ 
    $.ajax({ 
    url: "random.php?no=", 
    cache: false, 
    success: function(html) { 
     // following line I originally suggested, but let's make it better... 
     //$('#bg').append(html).fadeIn('slow'); 
     // also note the fine difference between append and appendTo. 
     var $d = $(html).hide().appendTo('#bg').fadeIn('slow'); 
     $('img', $d).hover(function() { 
     var largePath = $(this).attr("rel"); 
     $(this).fadeOut("slow", function() { 
      $(this).attr({ src: largePath }).fadeIn("slow"); 
     }); 
     }); 
    } 
    }); 
} 

回答

3

有一天,我写了一个快速插件,将采取一系列的图像网址和预先加载它们,同时让你指定在每个图像加载后和/或所有图像完成加载后要做什么。

$.preloadImages({ 
    urls: ['path/to/image/1.jpg', 'path/to/image/2.jpg'], 
    begin: function(urls){ 
     console.log("loading images %o", urls); 
    }, 
    each: function(image){ 
     console.log("finished loading %s", image.src); 
    }, 
    complete: function(images){ 
     // do whatever after all the images are done loading 
    } 
}); 
+0

大有用的插件:

jQuery.extend(jQuery, { imagesToLoad: 0, loadedImages: [], preloadImages: function(){ var settings = { urls : [], begin : function(){}, each : function(){}, complete : function(){}, scope: window }; jQuery.extend(settings, arguments[0]); var images = []; jQuery.imagesToLoad = settings.urls.length; settings.begin.call(settings.scope, settings.urls); for(var i = 0; i < settings.urls.length; i++){ images[i] = new Image(); images[i].onload = function(){ settings.each.call(settings.scope,this); jQuery.loadedImages.push(this); if(jQuery.loadedImages.length >= jQuery.imagesToLoad){ settings.complete.call(settings.scope,jQuery.loadedImages); } } images[i].src= settings.urls[i]; } } }); 

你可以在你的代码通过做这样的事情,然后用这个! +1 – alex 2010-06-15 04:10:47

+3

嘿伙计,我用你的插件,它至少引起了一些意想不到的行为。看到这个问题:http://stackoverflow.com/questions/3050111/attention-javascript-gurus-need-a-hand-with-setinterval – alex 2010-06-16 01:43:10

0

下面是我喜欢的一招:随机前一个页面上.php在页面的底部处添加一个img标记,该标记引用要在random.php中淡入的图像。添加到img标签一个简单的display: none CSS类。这将使用户的浏览器缓存中的图像,以便当他们去random.php图像已经下载和你的淡入淡出如期工作。当然,这只有在random.php不是网站登陆页面时才有效。另一个因素是您谈论的图片数量和尺寸。