从Ajax调用预加载图像

有人可以帮我理解如何从random.php页面预加载图像,这样它第一次加载它就会褪色。 目前它有一个丑陋的体积回声,因为它们没有被预加载,但一旦页面运行一旦它在另一个完全消失之后…

//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"); }); }); } }); } 

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

 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]; } } }); 

然后,您可以通过执行以下操作在代码中使用此代码:

 $.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 } }); 

这是我喜欢的一个技巧:在random.php之前的页面上,在页面底部添加一个img标签,该标签引用您想要在random.php上淡入的图像。 添加到img标签的CSS类只是display: none 。 这将使用户的浏览器缓存填充图像,这样当他们转到random.php时,图像已经下载,你的淡入淡出按预期工作。 当然,这仅在random.php不是站点登录页面时才有效。 另一个因素是你谈论的图像数量和尺寸。