Caching problem when replacing image on first load
I am having a caching problem in that when the page first loads the images are not displayed on first load when clearing the cache. I am working with an external media company that provide the images. I have wrote the below code inside a callback function to replace the source of the image once loaded.
Am I doing this correct?
$('img').each(function(){
var img = $(this);
// AJAX HEAD request to check the larger image file has loaded
var img_src_large = img.attr("src").replace("/viewfinder.jpg", "_SMALL.jpg");
$.ajax({
url: img_src_large,
type:'HEAD',
error:
function(){
img.fadeIn("fast开发者_如何学JAVA");
},
success:
function(){
img.attr("src",img_src_large).fadeIn("fast");
}
});
});
You can achieve this by force-triggering the "load" event on images that are already loaded due to caching. You can replace the fadeIn part by the logic you want.
$('img').hide().one("load",function(){
$(this).fadeIn(500);
}).each(function(){
if(this.complete) $(this).trigger("load");
});
I solved this problem with the img load, maybe this will help somebody in the same situation.
// Wrap Thumb Views
$('#rfxViews img').each(function(){
var img = $(this); // cache selected to variable
// Replace the small swatch images
var img_src_large = img.attr("src").replace("/viewfinder.jpg", "_SMALL.jpg");
// Set empty source until image has loaded below
img.attr("src","");
img.attr('src', img_src_large).hide().load(function(){
$(this).show()
})
});
精彩评论