强制缓存控制:无缓存在Chrome浏览器通过XMLHttpRequest在F5重新加载
Force Cache-Control: no-cache in Chrome via XMLHttpRequest on F5 reload
我想确保通过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");
相关文章:
- 单击F5时如何停止页面加载
- 如何在从浏览缓存加载页面时执行javascript
- ReactJS和SpringDataRest缓存问题可能与websocket有关
- 缓存谷歌地图数据
- 如何在火狐浏览器中禁用F5和刷新
- 防止jQuery Mobile中的ajax缓存
- image.onload事件和浏览器缓存
- Javascript清除缓存以清除基本身份验证凭据
- 使用jquery.load('pageName')方法时,未从应用程序缓存加载Html页
- 将脚本缓存到本地存储的basket.js概念仍然是一个好主意吗
- 如何在用户按下F5键或单击浏览器时显示自定义的fancybox's后退/关闭按钮
- 阻止选项卡缓存jquery ui
- 强制浏览器更新缓存的HTML5视频对象
- 在Javascript中使用全局变量作为缓存是很好的
- 缓存!saveLocations()和addLocation()函数有什么区别
- 微软边缘浏览器缓存中的RESTful Angular应用程序
- 浏览器坚持使用旧的html和JS缓存
- 在jquery中按Ctrl+F5清除浏览器缓存
- 如何在使用完全缓存的情况下触发 F5 键并手动重新加载页面
- 强制缓存控制:无缓存在Chrome浏览器通过XMLHttpRequest在F5重新加载