location.reload with cache

location.reload with cache

本文关键字:cache with reload location      更新时间:2023-09-26

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

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

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

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

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

(注意:通过将filemtime附加为查询字符串,我已经对脚本等链接文件进行了缓存破坏管理)

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

我实现的解决方案如下:

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'],则可以安全地使用它。