我正在寻找一个快速和简单的方法,预加载图像与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插件在那里做这个,但他们似乎都有点大(大小);我只需要一个快速,简单和短的方式预加载图像!


当前回答

用jQuery预加载图像并获得回调函数的一个快速、无插件的方法是一次性创建多个img标记并计算响应。

function preload(files, cb) {
    var len = files.length;
    $(files.map(function(f) {
        return '<img src="'+f+'" />';
    }).join('')).load(function () {
        if(--len===0) {
            cb();
        }
    });
}

preload(["one.jpg", "two.png", "three.png"], function() {
    /* Code here is called once all files are loaded. */
});
​    ​

注意,如果你想支持IE7,你需要使用这个稍微不那么漂亮的版本(它也适用于其他浏览器):

function preload(files, cb) {
    var len = files.length;
    $($.map(files, function(f) {
        return '<img src="'+f+'" />';
    }).join('')).load(function () {
        if(--len===0) {
            cb();
        }
    });
}

其他回答

    jQuery.preloadImage=function(src,onSuccess,onError)
    {
        var img = new Image()
        img.src=src;
        var error=false;
        img.onerror=function(){
            error=true;
            if(onError)onError.call(img);
        }
        if(error==false)    
        setTimeout(function(){
            if(img.height>0&&img.width>0){ 
                if(onSuccess)onSuccess.call(img);
                return img;
            }   else {
                setTimeout(arguments.callee,5);
            }   
        },0);
        return img; 
    }

    jQuery.preloadImages=function(arrayOfImages){
        jQuery.each(arrayOfImages,function(){
            jQuery.preloadImage(this);
        })
    }
 // example   
    jQuery.preloadImage(
        'img/someimage.jpg',
        function(){
            /*complete
            this.width!=0 == true
            */
        },
        function(){
            /*error*/
        }
    )

我有一个小插件处理这个。

它被称为waitForImages,它可以处理img元素或CSS中任何引用图像的元素,例如div {background: url(img.png)}。

如果你只是想加载所有的图像,包括在CSS中引用的图像,这里是你如何做的:)

$('body').waitForImages({
    waitForAll: true,
    finished: function() {
       // All images have loaded.
    }  
});

我想用谷歌地图API自定义覆盖来做到这一点。他们的示例代码简单地使用JS插入IMG元素,并显示图像占位符框,直到图像被加载。我在这里找到了一个适合我的答案:https://stackoverflow.com/a/10863680/2095698。

$('<img src="'+ imgPaht +'">').load(function() {
$(this).width(some).height(some).appendTo('#some_target');
});

这将像前面建议的那样预加载图像,然后在加载img URL后使用处理程序追加img对象。jQuery的文档警告说,缓存的图像不能很好地与这个事件/处理程序代码一起工作,但它在FireFox和Chrome中为我工作,我不必担心IE。

简单快捷:

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();

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调用上预加载图像的解决方案的人。