There are three scenarios when a web page refreshes:
- Honors your cache (does not make resource requests).
- Verifies your cache (causes resources to generate 304s).
- Ignores your cache (causes resources to generate 200s).
For a simple page refresh you want your webpage to generate as few server requests as possible. There any many ways to refresh a page in JavaScript, however they can all have different and sometimes undesirable results. Let's look some code snippets of the aforementioned scenarios in reverse order.
3. Ignore Cache
window.location.reload(true);
This scenario is not usually necessary unless you know that the resources of your page have been updated. Also, using a good minification framework is probably a better way of ensuring that your clients always consume the latest resources with every request.
2. Verify Cache
window.location.reload();
This is obvious similar to the first call, only we are calling an override of the reload method that tells the browser to respect cache. However, this will still cause a series of 304 requests!
1. Honor Cache
window.location.href = window.location.href;
This is obviously a very simple way to refresh the page, and it will honor cache without forcing 304 requests. However, this will not work if your includes a hash tag.
jQuery Plugin
This little jQuery plugin will refresh the page and try to cause as few resource requests as possible.
(function($) {
$.refreshPage = refreshPage;
function refreshPage(reload) {
if (reload === true) {
window.location.reload(true);
return;
}
var i = window.location.href.indexOf('#');
if (i === -1) {
// There is no hash tag, refresh the page.
window.location.href = window.location.href;
} else if (i === window.location.href.length - 1) {
// The hash tag is at the end, just strip it.
window.location.href = window.location.href.substring(i);
} else {
// There is a legit hash tag, reload the page.
window.location.reload(false);
}
}
})(jQuery);
Enjoy,
Tom
No comments:
Post a Comment