Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

javascript - 用jQuery预加载图像(Preloading images with jQuery)

I'm looking for a quick and easy way to preload images with JavaScript.

(我正在寻找一种快速简单的方法来用JavaScript预加载图像。)

I'm using jQuery if that's important.

(如果重要的话,我正在使用jQuery。)

I saw this here ( http://nettuts.com... ):

(我在这里( 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" });
  }
};

But, it looks a bit over-the-top for what I want!

(但是,对于我想要的东西来说似乎有点过高了!)

I know there are jQuery plugins out there that do this but they all seem a bit big (in size);

(我知道那里有执行此操作的jQuery插件,但它们似乎都很大(大小);)

I just need a quick, easy and short way of preloading images!

(我只需要一种快速,轻松和简短的预加载图像方式!)

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Quick and easy:

(快速简单:)

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'
]);

Or, if you want a jQuery plugin:

(或者,如果您想要一个jQuery插件:)

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

// Usage:

$(['img1.jpg','img2.jpg','img3.jpg']).preload();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...