使用jQuery预加载图像我正在寻找一种使用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插件可以做到这一点,但它们看起来都有点大(大小); 我只需要快速,简单和简短的预加载图像方式!
4 回答
心有法竹
TA贡献1866条经验 获得超5个赞
快速和简单的:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});}// Usage:preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg']);或者,如果你想要一个jQuery插件:
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});}// Usage:$(['img1.jpg','img2.jpg','img3.jpg']).preload();
守着星空守着你
TA贡献1799条经验 获得超8个赞
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调用上预加载图像的解决方案。
添加回答
举报
0/150
提交
取消
