HTML and CSS Reference
In-Depth Information
There's a catch, however. Even if the browser sees during page load that the manifest
file has changed, it still lets the current page load continue immediately, with the now
out-of-date
appcache
contents; it then asks for the updated files to be loaded in the
background, to be ready for the
next
page load.
Fortunately, the browser provides a JavaScript API to help: the
applicationCache
in-
terface. Using this interface, you can detect that a new set of
appcache
contents has been
fetched and is now available, and force them to be applied to the
appcache
right away,
rather than on the next page load:
var cache =
applicationCache
;
cache.
addEventListener
(
"updateready"
, function(){
if (
cache.stats == cache.UPDATEREADY
) {
cache.
swapCache()
; // swap in the new cache items
}
}, false);
This makes the new
appcache
items available for any further uses during the current
page lifetime.
However, any places where the resources were already used on the page are not upda-
ted. That can result in a strange user experience, depending on the situation.
The cleanest way to force the entire page to be updated with the new resource versions
is to simply reload the page. However, be kind to the user, and first ask if he wants to
reload the page, like this:
var cache = applicationCache;
cache.addEventListener("updateready", function(){
if (cache.stats == cache.UPDATEREADY) {
if (
confirm
("This site has been updated. Do you want to reload?")) {
location.reload();
}
}
}, false);
So far, we've only seen how to respond to cases where the
appcache
is marked for
updating during a page load. However, some sites are designed to be long-lived, with
few or no page reloads. In this case, getting updates requires special handling.
To force the browser to do a check for an updated
cache.manifest
file and fetch the
appcache
contents if the file has been modified, you can call the
update()
API method:
function updateAppcache(){
var cache = applicationCache;
cache.
update()
; // check to see if the cache manifest file has been updated
cache.addEventListener("updateready", function(){
if (cache.stats == cache.UPDATEREADY) {
if (confirm("This site has been updated. Do you want to reload?")) {
location.reload();
}
}