Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  11] [ 2]  / answers: 1 / hits: 50767  / 15 Years ago, sat, may 23, 2009, 12:00:00

I'm fully aware that this question has been asked and answered everywhere, both on SO and off. However, every time there seems to be a different answer, e.g. this, this and that.



I don't care whether it's using jQuery or not - what's important is that it works, and is cross-browser.]



So, what is the best way to preload images?


More From » jquery

 Answers
3

Unfortunately, that depends on your purpose.
If you plan to use the images for purposes of style, your best bet is to use sprites.
http://www.alistapart.com/articles/sprites2



However, if you plan to use the images in <img> tags, then you'll want to pre-load them with



function preload(sources)
{
var images = [];
for (i = 0, length = sources.length; i < length; ++i) {
images[i] = new Image();
images[i].src = sources[i];
}
}


(modified source taken from What is the best way to preload multiple images in JavaScript?)



using new Image() does not involve the expense of using DOM methods but a new request for the image specified will be added to the queue. As the image is, at this point, not actually added to the page, there is no re-rendering involved. I would recommend, however, adding this to the end of your page (as all of your scripts should be, when possible) to prevent it from holding up more critical elements.



Edit: Edited to reflect comment quite correctly pointing out that separate Image objects are required to work properly. Thanks, and my bad for not checking it more closely.



Edit2: edited to make the reusability more obvious



Edit 3 (3 years later):



Due to changes in how browsers handle non-visible images (display:none or, as in this answer, never appended to the document) a new approach to pre-loading is preferred.



You can use an Ajax request to force early retrieval of images. Using jQuery, for example:



jQuery.get(source);


Or in the context of our previous example, you could do:



function preload(sources)
{
jQuery.each(sources, function(i,source) { jQuery.get(source); });
}


Note that this doesn't apply to the case of sprites which are fine as-is. This is just for things like photo galleries or sliders/carousels with images where the images aren't loading because they are not visible initially.



Also note that this method does not work for IE (ajax is normally not used to retrieve image data).


[#99469] Wednesday, May 20, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makiyac

Total Points: 470
Total Questions: 100
Total Answers: 115

Location: Botswana
Member since Sat, Jan 7, 2023
1 Year ago
makiyac questions
Sun, Jan 16, 22, 00:00, 2 Years ago
Thu, Dec 17, 20, 00:00, 4 Years ago
Fri, Dec 4, 20, 00:00, 4 Years ago
;