小编典典

用jQuery预加载图像

javascript

我正在寻找一种快速简单的方法来用JavaScript预加载图像。如果重要的话,我正在使用jQuery。

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插件,但它们看上去都很大(大小);我只需要一种快速,轻松和简短的方式来预加载图像!


阅读 414

收藏
2020-04-22

共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();
2020-04-22