使用 jQuery 预加载图像 [英] Preloading images with jQuery
本文介绍了使用 jQuery 预加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种快速简便的方法来使用 JavaScript 预加载图像.如果这很重要,我会使用 jQuery.
I'm looking for a quick and easy way to preload images with JavaScript. I'm using jQuery if that's important.
我在这里看到了这个(http://nettuts.com...):
I saw this here (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!
我知道有 jQuery 插件可以做到这一点,但它们看起来都有些大(大小);我只需要一种快速、简单和简短的方法来预加载图像!
I know there are jQuery plugins out there that do this but they all seem a bit big (in size); I just need a quick, easy and short way of preloading images!
推荐答案
快速和简单:
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 插件:
Or, if you want a jQuery plugin:
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
$(['img1.jpg','img2.jpg','img3.jpg']).preload();
这篇关于使用 jQuery 预加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文