Tag Archives: html5

Update offline application cache

You can automate this. To update users to the newest version of your site, set a listener to monitor the updateready event on page load:

// storage interface, for more details storage implemments see https://gist.github.com/allex/a9b431ebcc921f2b309d
var storage = {
  get: function(k) {},
  set: function(k, v) {},
  remove: function(k) {}
};

window.onload = function(e) {
  var appCache = window.applicationCache;
  if (!appCache) { return; }

  // update offline.manifest caches if possible.
  appCache.addEventListener('updateready', function(e) {
    if (appCache.status === appCache.UPDATEREADY) {
      // Browser downloaded a new app cache.
      // Swap it in and reload the page to get the new hotness.
      try { appCache.swapCache(); } catch (e) {}
      if ( confirm('A new version of this site is available. Load it?') ) {
        storage.set('reload_flag', 1);
        reload();
      }
    }
    else {
      // Manifest didn't changed. Nothing new to server.
    }
  }, false);

  // The manifest returns 404 or 410, the download failed,
  // or the manifest changed while the download was in progress.
  appCache.addEventListener('error', function(e) {
    var reload_flag = parseInt(storage.get('reload_flag'), 10) || 0;
    if (navigator.onLine && reload_flag > 0) {
      storage.set('reload_flag', 0);
      reload();
    }
  }, false);

  function reload() {
    window.location.reload();
  }
};

Reference Links: