强制缓存控制:无缓存在Chrome浏览器通过XMLHttpRequest在F5重新加载

Force Cache-Control: no-cache in Chrome via XMLHttpRequest on F5 reload

本文关键字:缓存 F5 新加载 加载 XMLHttpRequest 控制 存在 浏览器 Chrome      更新时间:2023-09-26

我想确保通过AJAX调用请求的数据是新鲜的,而不是缓存的。因此,我发送标题Cache-Control: no-cache

但是我的Chrome版本33覆盖这个标题与Cache-Control: max-age=0,如果用户按下F5。

的例子。在你的web服务器上放一个test.html,内容为

<script>
    var xhr = new XMLHttpRequest;
    xhr.open('GET', 'test.html');
    xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send();
</script>

在网络选项卡上的chrome调试器中,我看到test.html AJAX调用。状态码200。现在按F5重新加载页面。有max-age: 0,状态码304 Not Modified。

Firefox显示类似的行为。而不是仅仅覆盖请求头,它修改为Cache-Control: no-cache, max-age=0在F5。

我可以抑制这个吗?

由于多种原因,使用查询字符串进行缓存控制并不是您目前的最佳选择,并且(仅)在此回答中提到了一些原因。他甚至解释了版本控制的新标准方法。如果你只是想设置你的请求头,正确的方法是:

    // via Cache-Control header:
    xhr.setRequestHeader("Cache-Control", "no-cache, no-store, max-age=0");
    
    // fallbacks for IE and older browsers:
    xhr.setRequestHeader("Expires", "Tue, 01 Jan 1980 1:00:00 GMT");
    xhr.setRequestHeader("Pragma", "no-cache"); //Edit: I noticed this is required for Chrome some time ago... forgot to mention here

另一种方法是在url后面附加一个唯一的数字。

<script>
    var xhr = new XMLHttpRequest;
    xhr.open('GET', 'test.html?_=' + new Date().getTime());
    //xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send();
</script>

时间戳不是唯一的,但是对于您的用例,它应该是唯一的。

我尝试(和失败)某种随机化的URL,但它没有工作,因为我正在访问的文件(.json)被缓存,以及

我的解决方案是在json文件名的调用中添加时间戳(类似于上面的方法,略有修改)。这对我来说非常有效(代码片段如下)。

doSomething('files/data.json?nocache=' + (new Date()).getTime(), function(text){...

我对这一切都很陌生,所以我相信这不是一个标准/正确的解决方案,但它对我来说很有效。

删除元素并添加一个新的元素与jQuery (JS也,我认为)在Chrome中为我工作。

// Wordpress Context, selectedImage is an object from the Media Selector Dialog
const imageID = selectedImage.id 
const imageURL = selectedImage.url   
// This is a div with the img as an only child
const logoImageContainer = $('#q1nv0-preview-image-container')
let clone = $(logoImageContainer).find('img').clone()
// In the cloned img object I change the src to the new image      
clone.removeAttr("src").attr('src', imageURL)
// Also I have to remove this in wordpress context:
clone.removeAttr("srcset")
// the div is cleared of the old image      
$('#q1nv0-preview-image-container').empty()
// the new image is added to the div
$(logoImageContainer).prepend(clone)
http.setRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");