Location.reload with cache

If you have a better heading for this question, feel free to edit.

For the longest time, I always used location.reload()to reload the page - this is the most logical thing to do, right?

But I recently noticed that this is not the equivalent of F5, as I originally thought, but more Ctrl + F5. All images and other related files were re-requested from the server when all I wanted to do was reload the page.

I found that I can use location.replace(location.href), and this seems to achieve the effect I want: reload the page, but get the related files from the cache.

Is that ideal? Is there a better way than this? Can I ignore any pitfalls this method may have?

(note: I already have control over the caching of related files, such as scripts, by adding filemtimeas a query string)

+5
source share
1 answer

In response to my own question, a massive error occurs: when the location contains a hash, the browser will go to that hash instead of reloading the page.

The solution I implemented is as follows:

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);
            }
    };
})();

Assuming nothing is used on the server side $_GET['__hash'], this can be safely used.

+4
source

All Articles