JP,检查完您的解决方案后,我在Firefox中仍然遇到问题,即在继续加载页面之前无法预加载图像。我通过sleep(5)
在服务器端脚本中放置一些脚本来发现这一点。我根据您的情况实施了以下解决方案,似乎可以解决此问题。
基本上,我向您的jQuery preload插件添加了一个回调,以便在正确加载所有图像之后调用该回调。
// Helper function, used below.
// Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
Array.prototype.remove = function(element) {
for (var i = 0; i < this.length; i++) {
if (this[i] == element) { this.splice(i,1); }
}
};
// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {
checklist = this.toArray();
this.each(function() {
$('<img>').attr({ src: this }).load(function() {
checklist.remove($(this).attr('src'));
if (checklist.length == 0) { callback(); }
});
});
};
在我的上下文中,出于兴趣,我按如下方式使用它:
$.post('/submit_stuff', { id: 123 }, function(response) {
$([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
// Update page with response data
});
});
希望这可以帮助从Google转到此页面的人(像我一样)寻找一种解决方案,以在Ajax调用中预加载图像。
$.each(arguments,function(){(new Image).src=this});