681 javascript 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" });
}
};
Run Code Online (Sandbox Code Playgroud)
但是,它看起来有点过头了我想要的东西!
我知道有jQuery插件可以做到这一点,但它们看起来都有点大(大小); 我只需要快速,简单和简短的预加载图像方式!
Jam*_*mes 962
快速和简单的:
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'
]);
Run Code Online (Sandbox Code Playgroud)
或者,如果你想要一个jQuery插件:
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
$(['img1.jpg','img2.jpg','img3.jpg']).preload();
Run Code Online (Sandbox Code Playgroud)
Den*_*ngo 100
这是第一个响应的调整版本,它实际上将图像加载到DOM中并默认隐藏它.
function preload(arrayOfImages) {
$(arrayOfImages).each(function () {
$('<img />').attr('src',this).appendTo('body').css('display','none');
});
}
Run Code Online (Sandbox Code Playgroud)
Gaj*_*jus 52
使用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');
});
Run Code Online (Sandbox Code Playgroud)
Dav*_*ave 35
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(); }
});
});
};
Run Code Online (Sandbox Code Playgroud)
出于兴趣,在我的上下文中,我使用如下:
$.post('/submit_stuff', { id: 123 }, function(response) {
$([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
// Update page with response data
});
});
Run Code Online (Sandbox Code Playgroud)
希望这有助于从Google访问此页面的人(正如我所做)寻找在Ajax调用上预加载图像的解决方案.
rkc*_*ell 25
这一行jQuery代码创建(并加载)一个DOM元素img而不显示它:
$('<img src="img/1.jpg"/>');
Run Code Online (Sandbox Code Playgroud)
yck*_*art 22
$.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;
});
};
Run Code Online (Sandbox Code Playgroud)
用法很简单:
$('img').preload(function(perc, done) {
console.log(this, perc, done);
});
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/yckart/ACbTK/
ale*_*lex 19
我有一个小插件来处理这个问题.
它被称为waitForImages,它可以处理img
元素或任何带有CSS中图像引用的元素,例如div { background: url(img.png) }
.
如果您只是想加载所有图像,包括CSS中引用的图像,以下是您将如何做到这一点:)
$('body').waitForImages({
waitForAll: true,
finished: function() {
// All images have loaded.
}
});
Run Code Online (Sandbox Code Playgroud)
alz*_*rke 13
这个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
}
});
Run Code Online (Sandbox Code Playgroud)
还有其他选项,例如是要同步还是异步加载图像,以及每个单独图像的完整事件.
its*_*sme 13
你可以使用css display:none;
规则在你的html中加载图像,然后用js或jquery显示它们
不要使用js或jquery函数来预加载只是一个css规则与许多js行要执行
例如:Html
<img src="someimg.png" class="hide" alt=""/>
Run Code Online (Sandbox Code Playgroud)
CSS:
.hide{
display:none;
}
Run Code Online (Sandbox Code Playgroud)
jQuery的:
//if want to show img
$('.hide').show();
//if want to hide
$('.hide').hide();
Run Code Online (Sandbox Code Playgroud)
通过jquery/javascript预加载图像并不好,因为图像在页面加载需要几毫秒才能解析和执行脚本,特别是如果它们是大图像,那么将它们隐藏在hml中对性能来说也更好因为图像真的是预先加载而根本没有看到,直到你显示出来!
在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. */
});
? ?
Run Code Online (Sandbox Code Playgroud)
请注意,如果你想支持IE7,你需要使用这个稍微不那么漂亮的版本(这也适用于其他浏览器):
function preload(files, cb) {
var len = files.length;
$($.map(files, function(f) {
return '<img src="'+f+'" />';
}).join('')).load(function () {
if(--len===0) {
cb();
}
});
}
Run Code Online (Sandbox Code Playgroud)
谢谢你!我会在JP的答案上加上一点点riff - 我不知道这是否会对任何人有所帮助,但是这样你就不必创建一个图像数组了,你可以预先加载你所有的大图像正确命名你的拇指.这很方便,因为我有一个人正在用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;
}
});
Run Code Online (Sandbox Code Playgroud)
基本上,对于页面上的每个图像,它抓取每个图像的src,如果它符合某些标准(是拇指或主页图像),它会更改名称(图像src中的基本字符串替换),然后加载图像.
在我的例子中,页面上充满了像image_th.jpg这样的拇指图像,所有相应的大图像都被命名为image_lg.jpg.拇指向大只用_lg.jpg替换_th.jpg然后预加载所有大图像.
希望这有助于某人.