In the gallery of products I have choice to choose a color of item, seria, or side view. Each option has own picture. When I click one of these options I have src-substitution of image, for the effect I'm using fadeIn/fadeOut, it looks like:
$('button').click(function(){
$('img').fadeOut("slow",function(){
$(this).attr("src",newSRC);
$(this).fadeIn("slow");
});
});
but when fadeIn completed The picture does not have time to draw, even if it has already been loaded into the cache and it's looking very wierd for the site-gallery intercoms
I can not use preCache all images, because if the products will be a count of over 100 items the site will loading whole day, in the main case at low connections. I wanted to remove item fully, and then use load, but I can't remove items 'caz the gallery will crash (it's a flexible site, I can't remove items, all will collapse). Now I did a little gif, but ... facepalm, sorry.
So what do you think the best solution could be ?
I'd start the loading of the new image right away (into a temporary image object) on the click so it's available sooner (perhaps even before the fadeOut is done) rather than waiting until you actually need it to start the loading. This will get the image into the browser cache so it will load immediately when you assign the src of the real image and there will be less waiting:
$('button').click(function(){
var imgLoaded = false, fadeDone = false;
var fadeTarget = $('img');
// fadeIn the new image when everything is ready
function fadeIfReady() {
if (imgLoaded && fadeDone) {
fadeTarget.attr("src", newSrc).fadeIn("slow");
}
}
// create temporary image for starting preload of new image immediately
var tempImg = new Image();
tempImg.onload = function() {
imgLoaded = true;
fadeIfReady();
};
tempImg.src = newSrc;
// start the fadeOut and do the fadeIn when the fadeOut is done or
// when the image gets loaded (whichever occurs last)
fadeTarget.fadeOut("slow",function(){
fadeDone = true;
fadeIfReady();
});
});
I would wait for the next image to load before fading it in, like:
var loadFail;
$('button').click(function(){
$('img').fadeOut("slow",function(){
$(this)
.attr("src",newSRC)
.load(function(){
$('img').fadeIn("slow");
clearTimeout(loadFail);
});
loadFail = setTimeout(function(){
$('img').fadeIn("slow");
}, 4000);
});
});