jQueryで画像をプリロードする 質問する

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 プラグインがあることは知っていますが、どれもサイズが少し大きいようです。必要なのは、画像をプリロードするための迅速で簡単、かつ短い方法だけです。

ベストアンサー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();

おすすめ記事