Javascript 使用jQuery预加载图像
我正在寻找一种快速简便的方法,用JavaScript预加载图像。如果这很重要的话,我正在使用jQuery 我在这里看到这个():Javascript 使用jQuery预加载图像,javascript,jquery,Javascript,Jquery,我正在寻找一种快速简便的方法,用JavaScript预加载图像。如果这很重要的话,我正在使用jQuery 我在这里看到这个(): 函数complexLoad(配置,文件名){ 对于(var x=0;x
函数complexLoad(配置,文件名){
对于(var x=0;x
我知道有一些jQuery插件可以做到这一点,但它们看起来都有点大(大小);我只需要一种快速、简单、快捷的方式来预加载图像!快速、简单:
函数预加载(数组图像){
$(arrayOfImages).each(函数(){
$('
或者,如果您想要jQuery插件:
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
$(['img1.jpg','img2.jpg','img3.jpg']).preload();
$.fn.preload=函数(){
这个。每个(函数(){
$('JP,在检查了您的解决方案后,我在Firefox中仍然遇到问题,在加载页面之前,Firefox无法预加载图像。我通过在服务器端脚本中添加一些sleep(5)
发现了这一点。我基于您的解决方案实现了以下解决方案,似乎可以解决这一问题
基本上,我向jQuery预加载插件添加了一个回调,以便在正确加载所有图像后调用它
// 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(); }
});
});
};
希望这能帮助那些从Google(和我一样)来到这个页面寻找在Ajax调用中预加载图像的解决方案的人。这个jquery插件只有1.39kb
用法:
$({}).imageLoader({
images: [src1,src2,src3...],
allcomplete:function(e,ui){
//images are ready here
//your code - site.fadeIn() or something like that
}
});
还有其他选项,如同步还是非同步加载图像,以及每个图像的完整事件。我有一个小插件来处理这个问题
它被调用,可以处理img
元素或CSS中引用图像的任何元素,例如div{background:url(img.png)}
如果您只是想加载所有图像,包括CSS中引用的图像,那么可以这样做:)
谢谢!我想在J-p的答案上加一点注释-我不知道这是否对任何人都有帮助,但这样你就不必创建一个图像数组,如果你的大拇指命名正确,你就可以预加载所有的大图像。这很方便,因为我有人用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的thumb图像,所有相应的大图像都名为image_lg.jpg。thumb to large只是将_th.jpg替换为_lg.jpg,然后预加载所有大图像
希望这对其他人有所帮助。这里是第一个响应的一个调整版本,它实际将图像加载到DOM中,并在默认情况下隐藏它
function preload(arrayOfImages) {
$(arrayOfImages).each(function () {
$('<img />').attr('src',this).appendTo('body').css('display','none');
});
}
函数预加载(数组图像){
$(arrayOfImages)。每个(函数(){
$('这一行jQuery代码创建(并加载)DOM元素img,但不显示它:
$('<img src="img/1.jpg"/>');
<代码>$('');
您可以使用cssdisplay:none;
规则将图像加载到html中的某个位置,然后在需要使用js或jquery时显示它们
不要使用js或jquery函数来预加载只是css规则,而不是要执行的许多行js
示例:Html
<img src="someimg.png" class="hide" alt=""/>
jQuery:
//if want to show img
$('.hide').show();
//if want to hide
$('.hide').hide();
通过jquery/javascript预加载图像是不好的,因为在页面中加载图像需要几毫秒的时间+解析和执行脚本需要几毫秒的时间,特别是如果它们是大图像,那么将它们隐藏在hml中也会更好地提高性能,因为图像确实是预加载的,根本看不到加载,直到您显示出来!功能预加载(imgs){
function preload(imgs) {
$(imgs).each(function(index, value) {
$('<img />').attr('src', value).appendTo('body').css('display', 'none');
});
}
$(imgs)。每个(函数(索引、值){
$('
.attr('src',value)
不
.attr('src',this)
只需指出:)在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. */
});
函数预加载(文件、cb){
var len=files.length;
$(files.map(函数(f)){
返回“”;
}).join(“”)).load(函数(){
如果(--len==0){
cb();
}
});
}
预加载([“one.jpg”、“two.png”、“three.png”],function()){
/*加载所有文件后,将调用此处的代码*/
});
请注意,如果您想支持IE7,您需要使用这个稍微不那么漂亮的版本(它也适用于其他浏览器):
函数预加载(文件、cb){
var len=files.length;
$($.map(文件、函数(f)){
返回“”;
}).join(“”)).load(函数(){
如果(--len==0){
cb();
}
});
}
使用JavaScript
此函数允许您在加载所有图片时触发回调。但是,请注意,如果至少有一个资源未加载,它将永远不会触发回调。通过实现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');
});
var preload pictures=函数(pictureUrls,回调){
var i,
J
加载=0;
对于(i=0,j=pictureUrls.length;i.hide{
display:none;
}
//if want to show img
$('.hide').show();
//if want to hide
$('.hide').hide();
function preload(imgs) {
$(imgs).each(function(index, value) {
$('<img />').attr('src', value).appendTo('body').css('display', 'none');
});
}
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. */
});
function preload(files, cb) {
var len = files.length;
$($.map(files, function(f) {
return '<img src="'+f+'" />';
}).join('')).load(function () {
if(--len===0) {
cb();
}
});
}
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');
});
$('<img src="' + imgURL + '"/>').on('load', function(){ doOnLoadStuff(); });
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*/
}
)
$.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);
});
$("#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";
$('<img src="'+ imgPaht +'">').load(function() {
$(this).width(some).height(some).appendTo('#some_target');
});
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