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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With