如果它需要控制缓存页面的更新,我有一个很好的方法来做到这一点。
- 向页面添加一些javascript,在加载时总是将页面的版本号作为字符串(ajax)获取。例如:
www.yoursite.com/page/about?getVer=1&__[date]
- 如果用户访问过该页面一次,则将其与存储的版本号(存储在 cookie 或 localStorage 中)进行比较,否则直接存储。
- 如果版本与本地版本不同,使用window.location.reload(true)刷新页面
- 您将看到页面上所做的任何更改。
此方法至少需要一个请求,即使不需要请求,因为它已经存在于本地浏览器缓存中。但是与完全不使用缓存相比,开销要少(以确保页面将显示正确的更新内容)。每个页面请求只需要几个字节,而不是每个页面的所有内容。
重要提示:版本信息请求必须在您的服务器上实现,否则它将返回整个页面。
www.yoursite.com/page/about?getVer=1&__[date] 返回的版本字符串示例:
skg2pl-v8kqb
为了给你一个代码示例,这里是我的库的一部分(我认为你不能使用它,但也许它会让你知道如何去做):
o.gCheckDocVersion = function() // Because of the hard caching method, check document for changes with ajax
{
var sUrl = o.getQuerylessUrl(window.location.href),
sDocVer = o.gGetData( sUrl, false );
o.ajaxRequest({ url:sUrl+'?getVer=1&'+o.uniqueId(), cache:0, dataType:'text' },
function(sVer)
{
if( typeof sVer == 'string' && sVer.length )
{
var bReload = (( typeof sDocVer == 'string' ) && sDocVer != sVer );
if( bReload || !sDocVer )
{
o.gSetData( sUrl, sVer );
sDocVer = o.gGetData( sUrl, false );
if( bReload && ( typeof sDocVer != 'string' || sDocVer != sVer ))
{ bReload = false; }
}
if( bReload )
{ // Hard refresh page contents
window.location.reload(true); }
}
}, false, false );
};
如果您使用与版本无关的资源,例如 javascript 或 css 文件,请添加版本号(通过 url 重写而不是查询来实现,因为它们大多不会被缓存)。例如:www.yoursite.com/ver-01/about.js
对我来说,这种方法效果很好,也许它也可以帮助你。