Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

location.reload with cache

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

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

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

I discovered that I could use location.replace(location.href) and this appears to achieve the effect I want: reload the page but retrieve linked files from cache.

Is this ideal? Is there a better way than this? Have I overlooked any pitfalls this method may have?

(note: I already have cache-busting management on linked files such as scripts, by appending the filemtime as a query string)

like image 304
Niet the Dark Absol Avatar asked Oct 07 '22 05:10

Niet the Dark Absol


1 Answers

In answer to my own question, there is a massive pitfall: When the location contains a hash, the browser will jump 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 on the server side uses $_GET['__hash'], this can be used safely.

like image 165
Niet the Dark Absol Avatar answered Oct 10 '22 07:10

Niet the Dark Absol