ApplicationCache of HTML for offline browsing in HTML5

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.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434