ApplicationCache of HTML for offline browsing in HTML5

By | June 11, 2012

Well, yet another offline storage can be the actual html that has been transferred from server. It is an important fact, that even if we use browser cache using cache header, the browser does not respond properly when offline as it does when one is online.  HTML5 introduces a new way of programming style which ensures that the browser cache can be used up to cache individual page of the website and these pages will work in the same way even in offline than it gets online.

To use application cache, we first need to understand that it works with a manifest file. Let us consider an example :

<html manifest="cache.appcache">

Here in the above code, the Html points to the cache file. We generally give extension as appcache to the external header. The content of this file is a plain text and will hold all the files that needs to be used as application cache.

The cache file contains :


CACHE MANIFEST
# version 1.0.0

CACHE:
/html5/src/logic.js
/html5/src/style.css
/html5/src/background.png

NETWORK:
*

Here we have specified the content of the manifest that needs to be cached. Here the background.png, style.css and logic.js will remain cached and will act normally to the browser as if the application is online. The Network * specifies all other files needed to be online. You can also define fallback for the cached manifest.

window.applicationCache.addEventListener('updateready', function(e) {

if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
}
}, false);

So in the above code we add an EventHandler to the updaterready event such that when cache update is ready it will show a dialog to reload the page automatically.

You can read more about it from here.

 

I hope this comes useful.

Thank you for reading.