Firefox重新加载页面上的图像

时间:2013-10-09 21:15:37

标签: html firefox caching web

我使用的是Firefox 24.0。问题(见标题)似乎不是一个缓存问题。图像实际上重新加载;但是,显示上一个图像,直到新图像可用。在我的情况下,这会生成一个页面,其中包含在不同时间刷新的图像,并且很难看到什么是新内容以及什么是旧内容。 IE和Chrome都没有这个问题,因为图像在新图像准备好之前不会显示。

我遇到的唯一解决方案是在图像网址中添加时间戳或randon编号,或者使用javascript隐藏图像直到图像加载,然后显示。但是,我想要一个更清晰的解决方案,如果可能的话,在服务器端,比如指定一些会让Firefox忘记旧图像的标题。

以下是显示恼人效果的代码。变体1在Firefox中不起作用:

<html>
<head></head>
<script type="text/javascript">
    function AddImage() {
        var imgElem = document.createElement('img');

        // Variant 1
        imgElem.setAttribute('src', 'http://localhost/ImageServer.asmx/GetImage');

        // Variant 2
        //imgElem.setAttribute('src', 'http://localhost/ImageServer.asmx/GetImage?r=' + Math.random());

        // Variant 3
        //imgElem.setAttribute('src', 'http://localhost/ImageServer.asmx/GetImage');
        //imgElem.style.display = 'none';
        //imgElem.setAttribute('onload', 'this.style.display = "block"');

        document.body.appendChild(imgElem);
    }
</script>
<body onload="AddImage()">
</body>
</html>

为了完整性,这里是服务器端代码,它是一种旧时尚的Web服务,它在两个图像之间交替显示延迟效果的延迟。

static int imgNumber = 2;

[WebMethod]
public void GetImage()
{
     Thread.Sleep(2000); // Delay to see the effect of the lingering image

     HttpContext.Current.Response.AppendHeader("Cache-Control", "private, max-age=0, s-maxage=0, no-cache, must-revalidate, proxy-revalidate");

     imgNumber = imgNumber % 2 + 1;
     string strPathPrefix = @"A:\Path\";
     HttpContext.Current.Response.WriteFile(strPathPrefix + imgNumber + ".png");
}

1 个答案:

答案 0 :(得分:1)

您的“变体2”方法,其中通过在末尾附加随机生成的数字来生成唯一的URL是完全有效的,并且是一种广泛使用的防止缓存的方法。

我强烈建议使用此而不是尝试修复缓存控制标头的问题,因为它们可能不可靠。有些CDN甚至会忽略缓存标头以试图节省带宽等。

相关问题