Preloading images into browser cache
I'm pretty much a newbie when it comes to JavaScript and jQuery, so bare with me if I make some obvious mistakes.
I am currently trying to create an image gallery that will show a lot of art. Therefore, there will be many images on the site. I noticed that when I view my code on another computer, the images take a while to load. So far on my computer, they were showing up right away, and I'm guessing this is because they are already cached.
So, I took a quick look to see if I could prevent this, and I found that a lot of people mention image preloading. However, I could not find a solution that matches my desire or an explanation that I could understand (I hate using code I don't understand). So I tried to go myself and it didn't work, but I felt the logic I was writing was correct, but needs tweaking. I am going to write my code below and any advice on what to do next would be greatly appreciated.
Image preload code:
var allImages = $(img).attr('src'); //select every image
var preloadImages = [];
//add images to empty array
for(var i = 0; i < allImages.length; i++ ) {
preloadImages.push(allImages[i]);
}
//then preload images
for(var i = 0; i < preloadImages.length; i++ ) {
new Image().src = preloadImages[i];
}
So this is the code I wrote to preload images to my page. Let me know where I am going wrong. I'm really not sure how am I going to select all the images on my website and load them into an array through which I can continue to loop?
Thanks for the answers, I guess I didn't explain my problem very well. Many image preloading solutions seem to be manually injected into each image src into and array. What I was looking for is a way to select each image I have and then put into an array without typing them in. Is it possible? My reason is that as I keep adding more and more images, it would be great if preloading could just take care of itself.
source to share
Problem
$(img).attr('src');
doesn't give you an array of all your images.
Try console.log
your variable allImages
and you only see the first attribute src
.
Decision
You can use $.map
:
var allImages = $('img');
var allImagesSrc = $.map(allImages, function (element){
return $(element).attr('src');
//Alternatively: return element.src
});
source to share