我正在寻找一个快速和简单的方法,预加载图像与JavaScript。如果这很重要,我将使用jQuery。
我在这里看到了这个(http://nettuts.com...):)
function complexLoad(config, fileNames) {
for (var x = 0; x < fileNames.length; x++) {
$("<img>").attr({
id: fileNames[x],
src: config.imgDir + fileNames[x] + config.imgFormat,
title: "The " + fileNames[x] + " nebula"
}).appendTo("#" + config.imgContainer).css({ display: "none" });
}
};
但是,对于我想要的东西来说,这看起来有点夸张!
我知道有jQuery插件在那里做这个,但他们似乎都有点大(大小);我只需要一个快速,简单和短的方式预加载图像!
使用JavaScript图像对象。
这个函数允许你在加载所有图片时触发一个回调。但是,请注意,如果至少有一个资源没有加载,它将永远不会触发回调。这可以通过实现onerror回调和增加加载值或处理错误来轻松修复。
var preloadPictures = function(pictureUrls, callback) {
var i,
j,
loaded = 0;
for (i = 0, j = pictureUrls.length; i < j; i++) {
(function (img, src) {
img.onload = function () {
if (++loaded == pictureUrls.length && callback) {
callback();
}
};
// Use the following callback methods to debug
// in case of an unexpected behavior.
img.onerror = function () {};
img.onabort = function () {};
img.src = src;
} (new Image(), pictureUrls[i]));
}
};
preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
console.log('a');
});
preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
console.log('b');
});
JP,在检查了您的解决方案后,我仍然在Firefox中有问题,在加载页面之前它不会预加载图像。我是通过在服务器端脚本中添加一些sleep(5)来发现这一点的。我实施了以下解决方案的基础上,似乎解决这个问题。
基本上,我添加了一个回调到你的jQuery预加载插件,这样它就会在所有图像都正确加载后被调用。
// 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
});
});
希望这能帮助那些从谷歌(和我一样)来到这个页面,寻找在Ajax调用上预加载图像的解决方案的人。