将光标移到/点击文章中的句子上,可以查看译文。      显示繁体中文内容    显示简体中文内容

Preloading images with jQuery
jQuery预载入图像

I'm looking for a quick and easy way to preload images with JavaScript.i'm using jQuery if that's important.

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!

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!

时间:

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 :


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

//Usage:

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

Here's a tweaked version of the first response that actually loads the images into DOM and hides it by default.


function preload(arrayOfImages) {
 $(arrayOfImages).each(function () {
 $('<img/>').attr('src',this).appendTo('body').css('display','none');
 });
}

Use JavaScript Image object.

This function allows you to trigger a callback upon loading all pictures.However, note that it will never trigger a callback if at least one resource is not loaded.this can be easily fixed by implementing onerror callback and incrementing loaded value or handling the error.


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

JP, after checking your solution, i was still having issues in Firefox where it wouldn't preload the images before moving along with loading the page.i discovered this by putting some sleep(5) in my server side script.i implemented the following solution based off yours which seems to solve this.

Basically i added a callback to your jQuery preload plugin, so that it gets called after all the images are properly loaded.


//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(); }
 });
 });
};

Out of interest, in my context, i'm using this as follows :


$.post('/submit_stuff', { id: 123 }, function(response) {
 $([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
//Update page with response data
 });
});

Hopefully this helps someone who comes to this page from Google (as i did) looking for a solution to preloading images on Ajax calls.

I have a small plugin that handles this.

It's called waitForImages and it can handle img elements or any element with a reference to an image in the CSS, e.g.div { background: url(img.png) }

If you simply wanted to load all images, including ones referenced in the CSS, here is how you would do it : )


$('body').waitForImages({
 waitForAll: true,
 finished: function() {
//All images have loaded.
 } 
});

this jquery imageLoader plugin is just 1.39 kb

usage :


$({}).imageLoader({
 images: [src1,src2,src3...],
 allcomplete:function(e,ui){
//images are ready here
 $(document).ready(function(){
//your code - site.fadeIn() or something like that
 });
 }
});

there are also other options like whether you want to load the images synchronously or asychronously and a complete event for each individual image.


$.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;
 });
};

The usage is quite simple :


$('img').preload(function(perc, done) {
 console.log(this, perc, done);
});

http://jsfiddle.net/yckart/ACbTK/

you can load images in your html somewhere using css display:none; rule, then show them when you want with js or jquery

don't use js or jquery functions to preload is just a css rule Vs many lines of js to be executed

example : 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();

Preloading images by jquery/javascript is not good cause images takes few milliseconds to load in page + you have milliseconds for the script to be parsed and executed, expecially then if they are big images, so hiding them in hml is better also for performance, cause image is really preloaded without beeing visible at all, until you show that!

Thanks for this! i'd liek to add a little riff on the J-P's answer - i don't know if this will help anyone, but this way you don't have to create an array of images, and you can preload all your large images if you name your thumbs correctly.this is handy because i have someone who is writing all the pages in html, and it ensures one less step for them to do - eliminating the need to create the image array, and another step where things could get screwed up.


$("img").each(function(){
 var imgsrc = $(this).attr('src');
 if(imgsrc.match('_th.jpg') || imgsrc.match('_home.jpg')){
 imgsrc = thumbToLarge(imgsrc);
 (new Image()).src = imgsrc; 
 }
});

Basically, for each image on the page it grabs the src of each image, if it matches certain criteria (is a thumb, or home page image) it changes the name(a basic string replace in the image src), then loads the images.

In my case the page was full of thumb images all named something like image_th.jpg, and all the corresponding large images are named image_lg.jpg. the thumb to large just replaces the _th.jpg with _lg.jpg and then preloads all the large images.

Hope this helps someone.

...