[英]Can I tell from javascript whether my page was hard refreshed?
I've given up on this, but I thought I'd post here out of curiosity. 我已经放弃了这一点,但我想我会因为好奇而在这里发帖。
What I call a "hard refresh" is the Ctrl+R or Shift+F5 that you do during development to see your changes. 我称之为“硬刷新”的是您在开发过程中执行的Ctrl + R或Shift + F5 ,以查看您的更改。
This causes the browser to add a Cache-Control: max-age=0
header to the request and "child" requests like images and scripts, etc. 这会导致浏览器向请求添加
Cache-Control: max-age=0
标头, 并为图像和脚本等添加“子”请求。
If you're doing your job, you'll get a 304
on everything but the resource that's changed. 如果你正在做你的工作,除了改变的资源外,你将得到
304
。 (Okay, well, see comments. This is assuming that other validators are sent based on browser caches.) (好的,请参阅注释。这是假设其他验证器基于浏览器缓存发送。)
So far, so good. 到现在为止还挺好。
The problem is that I'm not loading scripts directly from the page, but through a load.js
, and the browsers are inconsistent about whether they include that Cache-Control
header on those requests. 问题是我不是直接从页面加载脚本,而是通过
load.js
加载脚本,并且浏览器在这些请求中是否包含该Cache-Control
标头时不一致。 Chrome doesn't do it at all, and Firefox seems to stop in the middle of a series. Chrome根本不会这样做,Firefox似乎停在了系列的中间。
Since I can't access the headers of the current request, there's no way to know whether that header should be included or not. 由于我无法访问当前请求的标头,因此无法知道是否应包含该标头。
The result is that when I change a script (other than load.js
), a hard refresh does not reliably work, and I have to, eg, clear the browser cache (which is a bit heavy-handed). 结果是,当我更改脚本(除了
load.js
)之外,硬刷新不能可靠地工作,我必须,例如,清除浏览器缓存(这有点沉重)。
Any thoughts on this? 有什么想法吗?
Unfortunately you cannot detect a hard refresh from JavaScript (there is no access to the headers for the currently loaded page). 遗憾的是,您无法从JavaScript检测到硬刷新(无法访问当前加载页面的标头)。
However, the server can tell from the request headers if this is a hard refresh, so there's the option of cooperating. 但是,服务器可以从请求标头中判断这是否是硬刷新,因此可以选择合作。 For example the server can include a custom
<meta>
tag in the response or add a special class to <body>
and your script will then have access to this information. 例如,服务器可以在响应中包含自定义
<meta>
标记,或者向<body>
添加一个特殊类,然后您的脚本就可以访问此信息。
Once load.js
detects a hard refresh it can then propagate it to the dependent scripts by eg attaching a URL parameter to the requests (think "?t=" + timestamp
). 一旦
load.js
检测到硬刷新,它就可以通过例如将URL参数附加到请求来将其传播到依赖脚本(想想"?t=" + timestamp
)。
You could try checking localStorage. 您可以尝试检查localStorage。 Set a localStorage variable and check it.
设置localStorage变量并进行检查。 If it's there, it's not a hard refresh, otherwise, it is a hard refresh.
如果它在那里,它不是一个硬刷新,否则,它是一个很难刷新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.