Motyar

@motyar

Freelance Web Developer

Static Web Hosting, made easy

Sep 14, 2011

Handling HTML5 Application Cache with JavaScript

HTML5 Application Cache provides a way to make your application work offline. HTML5 also provides a JavaScript API to handle Application Cache.

The window.applicationCache can be used to access browser's app cache with JavaScript.

We can check current state of the cache using its status property. It may have six different values.

var appCache = window.applicationCache;

switch (appCache.status) {
  case appCache.UNCACHED: // UNCACHED == 0
    return 'UNCACHED';
    break;
  case appCache.IDLE: // IDLE == 1
    return 'IDLE';
    break;
  case appCache.CHECKING: // CHECKING == 2
    return 'CHECKING';
    break;
  case appCache.DOWNLOADING: // DOWNLOADING == 3
    return 'DOWNLOADING';
    break;
  case appCache.UPDATEREADY:  // UPDATEREADY == 4
    return 'UPDATEREADY';
    break;
  case appCache.OBSOLETE: // OBSOLETE == 5
    return 'OBSOLETE';
    break;
  default:
    return 'UKNOWN CACHE STATUS';
    break;
};

To update the cache, first call applicationCache.update() method. This will attempt to update the user's cache (which requires the manifest file to have changed). Finally, when the applicationCache.status is in its UPDATEREADY state, calling applicationCache.swapCache() will change the old cache for the new one.

update() and swapCache() simply tells the browser to check for a new manifest, but does not updated resources to users.

To update users to the newest version of site, set a listener to monitor the updateready event on page load:

// on page load.
window.addEventListener('load', function(e) {
  //Check if a new cache is available 
  window.applicationCache.addEventListener('updateready', function(e) {
    if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
      // Browser downloaded a new app cache.
      // Swap it in and reload the page to get the new version.
      window.applicationCache.swapCache();
      if (confirm('A new version of this site is available. Load it?')) {
        window.location.reload();
      }
    } else {
      // Manifest didn't changed. Nothing new yet.
    }
  }, false);

}, false);

Labels: , ,




By :