使用 jQuery 预加载图像

2022-08-29 22:34:33

我正在寻找一种快速简便的方法来使用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插件可以做到这一点,但它们似乎都有点大(大小);我只需要一种快速,简单和简短的预加载图像的方法!


答案 1

快捷方便:

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

答案 2

下面是第一个响应的调整版本,它实际上将图像加载到 DOM 中,并默认将其隐藏。

function preload(arrayOfImages) {
    $(arrayOfImages).each(function () {
        $('<img />').attr('src',this).appendTo('body').css('display','none');
    });
}