【问题标题】:location.reload with cachelocation.reload 与缓存
【发布时间】:2012-07-14 04:43:49
【问题描述】:

如果您对此问题有更好的标题,请随时编辑。

在很长一段时间里,我总是使用location.reload() 重新加载页面 - 这是最合乎逻辑的做法,对吧?

但我最近注意到它并不像我最初想象的那样等同于 F5,而更像是 Ctrl+F5。所有图像和其他链接文件都从服务器重新请求,而我只想重新加载页面。

我发现我可以使用location.replace(location.href),这似乎达到了我想要的效果:重新加载页面但从缓存中检索链接文件。

这是理想的吗?还有比这更好的方法吗?我是否忽略了这种方法可能存在的任何缺陷?

(注意:我已经通过将filemtime 附加为查询字符串来对链接文件(例如脚本)进行缓存清除管理)

【问题讨论】:

标签: javascript caching reload


【解决方案1】:

在回答我自己的问题时,有一个很大的陷阱:当位置包含哈希时,浏览器将跳转到该哈希而不是重新加载页面。

我实现的解决方案如下:

reload = (function() {
    var m = location.search.match(/[?&]__hash=([^&]+)/);
    if( m) location.hash = unescape(m[1]);
    return function() {
            var h = location.hash;
            if( h == "") {
                    location.replace(location.href);
            }
            else {
                    var s = location.search;
                    s = s.replace(/[?&]__hash=[^&]+/,'');
                    s += (s == "" ? "?" : "&")+"__hash="+escape(h);
                    location.replace(location.pathname+s);
            }
    };
})();

假设服务器端没有使用$_GET['__hash'],则可以安全使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 2021-09-30
    • 1970-01-01
    • 2016-06-12
    • 2017-11-19
    相关资源
    最近更新 更多