2011-07-03 153 views
2

我遇到缓存问题,因为当第一次加载图像时,第一次加载时不显示图像时清除缓存。我正在与提供图像的外部媒体公司合作。我在回调函数中写了下面的代码来替换一次加载的图像的源代码。在第一次加载时替换图像时缓存问题

我做得对吗?

$('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"); 
      }, 
     success: 
      function(){ 
       img.attr("src",img_src_large).fadeIn("fast"); 
      } 
    }); 

}); 
+0

我偶然发现了这篇博客文章,虽然我无法使其发挥作用。 http://www.bennadel.com/blog/1007-jQuery-Attr-Function-Doesn-t-Work-With-IMAGE-complete.htm#comments_16704 –

+0

我刚刚在这里做了两次尝试,你试图欺骗浏览器通过ajax请求读取图像来缓存它? –

+0

使用AJAX只是一个例子,我试图让它工作。我所要做的就是用replace()更改图像的来源。这工作正常,如果图像在浏览器缓存中,但不是第一次加载 –

回答

1

您可以通过力触发已装入由于缓存图像“load”事件实现这一目标。你可以用你想要的逻辑来替换fadeIn部分。

$('img').hide().one("load",function(){ 
    $(this).fadeIn(500); 
}).each(function(){ 
    if(this.complete) $(this).trigger("load"); 
}); 
0

我用img加载解决了这个问题,也许这会帮助有人在相同的情况下。

// 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() 
    }) 

}); 
相关问题