我正在寻找一种快速简单的方法来用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楼
您可以使用css display:none;
在html的某处加载图像display:none;
规则,然后在需要使用js或jquery时显示它们
不要使用js或jquery函数来预加载只是一个CSS规则,而要执行的js行很多
范例:HTML
<img src="someimg.png" class="hide" alt=""/>
CSS:
.hide{
display:none;
}
jQuery的:
//if want to show img
$('.hide').show();
//if want to hide
$('.hide').hide();
通过jquery / javascript预加载图片效果不好,原因是图片需要花费几毫秒的时间才能加载到页面中+您有几毫秒的时间来解析和执行脚本,特别是如果它们是大图片,那么将它们隐藏在hml中也会带来更好的性能,导致图像真正被预加载而根本看不到蜂鸣声,直到您显示为止!
#2楼
function preload(imgs) {
$(imgs).each(function(index, value) {
$('<img />').attr('src', value).appendTo('body').css('display', 'none');
});
}
.attr('src',value)
不是.attr('src',this)
只是指出来:)
#3楼
快速,无插件的在jQuery中预加载图像并获得回调函数的方法是一次创建多个img
标签并计算响应,例如
function preload(files, cb) {
var len = files.length;
$(files.map(function(f) {
return '<img src="'+f+'" />';
}).join('')).load(function () {
if(--len===0) {
cb();
}
});
}
preload(["one.jpg", "two.png", "three.png"], function() {
/* Code here is called once all files are loaded. */
});
请注意,如果您想支持IE7,则需要使用这个不太漂亮的版本(在其他浏览器中也可以使用):
function preload(files, cb) {
var len = files.length;
$($.map(files, function(f) {
return '<img src="'+f+'" />';
}).join('')).load(function () {
if(--len===0) {
cb();
}
});
}
#4楼
使用JavaScript Image对象 。
此功能允许您在加载所有图片时触发回调。 但是,请注意,如果没有加载至少一个资源,它将永远不会触发回调。 这可以通过实现onerror
回调并增加loaded
值或处理错误来轻松解决。
var preloadPictures = function(pictureUrls, callback) {
var i,
j,
loaded = 0;
for (i = 0, j = pictureUrls.length; i < j; i++) {
(function (img, src) {
img.onload = function () {
if (++loaded == pictureUrls.length && callback) {
callback();
}
};
// Use the following callback methods to debug
// in case of an unexpected behavior.
img.onerror = function () {};
img.onabort = function () {};
img.src = src;
} (new Image(), pictureUrls[i]));
}
};
preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
console.log('a');
});
preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
console.log('b');
});
#5楼
即使在IE9中,这也对我有效:
$('<img src="' + imgURL + '"/>').on('load', function(){ doOnLoadStuff(); });
#6楼
jQuery.preloadImage=function(src,onSuccess,onError)
{
var img = new Image()
img.src=src;
var error=false;
img.onerror=function(){
error=true;
if(onError)onError.call(img);
}
if(error==false)
setTimeout(function(){
if(img.height>0&&img.width>0){
if(onSuccess)onSuccess.call(img);
return img;
} else {
setTimeout(arguments.callee,5);
}
},0);
return img;
}
jQuery.preloadImages=function(arrayOfImages){
jQuery.each(arrayOfImages,function(){
jQuery.preloadImage(this);
})
}
// example
jQuery.preloadImage(
'img/someimage.jpg',
function(){
/*complete
this.width!=0 == true
*/
},
function(){
/*error*/
}
)
#7楼
$.fn.preload = function (callback) {
var length = this.length;
var iterator = 0;
return this.each(function () {
var self = this;
var tmp = new Image();
if (callback) tmp.onload = function () {
callback.call(self, 100 * ++iterator / length, iterator === length);
};
tmp.src = this.src;
});
};
用法很简单:
$('img').preload(function(perc, done) {
console.log(this, perc, done);
});
http://jsfiddle.net/yckart/ACbTK/
#8楼
我使用以下代码:
$("#myImage").attr("src","img/spinner.gif");
var img = new Image();
$(img).load(function() {
$("#myImage").attr("src",img.src);
});
img.src = "http://example.com/imageToPreload.jpg";
#9楼
我想通过Google Maps API自定义叠加层实现此目的。 他们的示例代码仅使用JS插入IMG元素,并显示图像占位符框,直到加载图像为止。 我在这里找到了一个对我有用的答案: https : //stackoverflow.com/a/10863680/2095698 。
$('<img src="'+ imgPaht +'">').load(function() {
$(this).width(some).height(some).appendTo('#some_target');
});
如之前建议的那样,这将预加载图像,然后在加载img URL后使用处理程序附加img对象。 jQuery的文档警告说,缓存的图像无法与此事件/处理程序代码一起很好地工作,但是它在FireFox和Chrome中对我有效,并且我不必担心IE。
#10楼
Coffeescript中的5行
array = ['/img/movie1.png','/img/movie2.png','/img/movie3.png']
$(document).ready ->
for index, image of array
img[index] = new Image()
img[index].src = image
#11楼
我将使用清单文件来告诉(现代)网络浏览器以加载所有相关图像并将其缓存。 使用Grunt和grunt-manifest自动执行此操作,无需再担心预加载脚本,缓存无效器,CDN等。
https://github.com/gunta/grunt-manifest
#12楼
对于那些只懂一点动作脚本的人,您可以轻松地检查Flash Player,并制作一个Flash预加载器,也可以将其导出到html5 / Javascript / Jquery。 要在未检测到Flash Player的情况下使用,请查看有关如何通过youtube角色回到html5 player来执行此操作的示例:)然后创建自己的Flash Player。 我没有详细信息,因为我还没有开始,如果我没有忘记,我将在稍后发布,并将尝试一些标准的Jquery代码来进行挖掘。
#13楼
JP,检查完您的解决方案后,我在Firefox中仍然遇到问题,即在继续加载页面之前无法预加载图像。 我是通过在服务器端脚本中添加sleep(5)
来发现这一点的。 我根据您的情况实施了以下解决方案,似乎可以解决此问题。
基本上,我向您的jQuery preload插件添加了一个回调,以便在正确加载所有图像之后调用该回调。
// Helper function, used below.
// Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
Array.prototype.remove = function(element) {
for (var i = 0; i < this.length; i++) {
if (this[i] == element) { this.splice(i,1); }
}
};
// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {
checklist = this.toArray();
this.each(function() {
$('<img>').attr({ src: this }).load(function() {
checklist.remove($(this).attr('src'));
if (checklist.length == 0) { callback(); }
});
});
};
在我的上下文中,出于兴趣,我按如下方式使用它:
$.post('/submit_stuff', { id: 123 }, function(response) {
$([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
// Update page with response data
});
});
希望这可以帮助从Google转到此页面的人(像我一样)寻找一种在Ajax调用中预加载图像的解决方案。
#14楼
快速简单:
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();
#15楼
这个jquery imageLoader插件只有1.39kb
用法:
$({}).imageLoader({
images: [src1,src2,src3...],
allcomplete:function(e,ui){
//images are ready here
//your code - site.fadeIn() or something like that
}
});
还有其他选项,例如您是否要同步或异步加载图像,以及每个图像的完整事件。
#16楼
我有一个小插件可以处理这个问题。
它称为waitForImages ,它可以处理img
元素或引用CSS中图像的任何元素,例如div { background: url(img.png) }
。
如果您只是想加载所有图像,包括CSS中引用的图像,请按以下步骤操作:)
$('body').waitForImages({
waitForAll: true,
finished: function() {
// All images have loaded.
}
});
#17楼
谢谢你! 我希望在JP的答案上加上一点即兴之处-我不知道这对任何人都没有帮助,但是这样一来,您不必创建图像阵列,并且可以预加载所有大图像正确命名您的拇指。 这很方便,因为我有一个用html编写所有页面的人,它确保了他们要做的少一步-消除了创建图像数组的需要,而另一步可能使事情搞砸了。
$("img").each(function(){
var imgsrc = $(this).attr('src');
if(imgsrc.match('_th.jpg') || imgsrc.match('_home.jpg')){
imgsrc = thumbToLarge(imgsrc);
(new Image()).src = imgsrc;
}
});
基本上,页面上的每个图像都会抓取每个图像的src,如果它符合特定条件(是拇指图像或主页图像),它将更改名称(图像src中的基本字符串替换),然后加载图像。
在我的情况下,页面上充满了拇指图像,所有图像均命名为image_th.jpg,所有相应的大图像均命名为image_lg.jpg。 大拇指将_th.jpg替换为_lg.jpg,然后预加载所有大图像。
希望这对某人有帮助。
#18楼
这是第一个响应的调整版本,该响应实际将图像加载到DOM中并默认隐藏它。
function preload(arrayOfImages) {
$(arrayOfImages).each(function () {
$('<img />').attr('src',this).appendTo('body').css('display','none');
});
}
#19楼
这段jQuery代码创建(并加载)一个DOM元素img而不显示它:
$('<img src="img/1.jpg"/>');