I would like to get some feedback on a image preloader i have implemented on a solution.
$(document).ready(function() {
// preload images
function preloadImages(images) {
var i, newImage;
for (i=0; i<images.length; i++){
newImage = new Image();
newImage.src = images[i];
}}
var imageSrc = new Array();
// preload images people
if($('.people img').length > 0) {
$('.people img').each(function(i) { imageSrc[i] = $(this).attr('src'); });
}
// preload slider images
if($('#slider img').length > 0) {
$('#slider img').each(function(i) { imageSrc[i] = $(this).attr('src'); });
}
var imageSrc = imageSrc.join(',');
preloadImages([imageSrc]);
});
Is it ok to do it that way?
In my head something like this should work fine
$(function() {
// Preload a specific set of images
$('.people img, #slider img').each(function() {
var img = new Image();
img.src = $(this).attr('src');
});
});
it looks good - like the simplicity
I have a question regarding swapping / mouseover images
My images are listed like this
<img src="wp-content/uploads/2011/04/Anja_Hansen_12.jpg" class="people" rel="wp-content/uploads/2011/04/Anja_Hansen_12_hover.jpg" />
I retrieve the mouseover image by the rel tag
How do i best preload those images? There quite a lot of images so it is vital with a good image preloader also for the mouseover image
Do i just add
$(function() {
// Preload a specific set of images
$('.people img, #slider img').each(function() {
var img = new Image();
img.src = $(this).attr('src');
img.src = $(this).attr('rel');
});
});
Try this
$(function() {
// Preload a specific set of images
$('.people img, #slider img').each(function() {
var img = new Image();
img.src = $(this).attr('src');
if (typeof $(this).attr('rel') !== 'undefined') {
var rel = new Image();
rel.src = $(this).attr('rel');
}
});
});
I rewrote the script a bit
But there seems to a loading issue. I have to confess that my page loads 136 pictures 202x302 20kb per picture.
My page keep loading for quite a while. Is it wrong to use each function?
// preload images
people = new Array();
people_swap = new Array();
$('body.category-people img').each(function(i) {
var obj = $(this);
people[i] = new Image();
people[i].src = obj.attr('src');
people_swap[i] = new Image();
if(obj.attr('data-hover') !== undefined) {
people_swap[i].src = obj.attr('data-hover');
}
});
$('.people img').hover(
function() {
var obj = $(this);
if(obj.attr('data-hover') !== undefined) {
var urlID = obj.attr('data-hover').split('#');
obj.attr('src') = people_swap[urlID[0]].src;
}
},
function() {
var urlID = $(this).attr('data-hover').split('#');
$(this).attr(src) = people[urlID[0]].src;
}
);
<img src="/wp-content/uploads/2011/04/test.jpg" data-hover="/wp-content/uploads/2011/05/test_hover.jpg#1" alt="" />
<img src="/wp-content/uploads/2011/04/test2.jpg" data-hover="/wp-content/uploads/2011/05/test2_hover.jpg#2" alt="" />