HTML5 offline web apps & debugging the cache manifest

During the build of the iPad web application we took into consideration the possibility that the end user would want to access the application at times when an internet connection was not available.

Of course you can get iPads with 3G however they are not as popular (due to pricing) as their wi-fi companions.

This is an obvious advantage that a lot of people would see over having the native application rather than a web application, but an advantage that doesn’t really exist.

Mobile web applications that run on browsers that support HTML5 (and lets face it, if you’re browsing on a mobile device the chances are the browser will be supporting HTML5) can take advantage of the Cache Manifest file and therefore allowing your application to run even when a connection isn’t available.

This handy file acts as a camping pack list for your web application, and while this post won’t go into the details of the contents of the Cache Manifest file, you can do a bit more reading about the HTML5 Cache Manifest if you’re just getting started.

One issue around the cache manifest is that it’s very difficult to debug to see if it’s working the way you want it to. That is where this handy bit of javascript comes in handy.

Simple copy and past this into your web application just before the closing </body> tag. Then you can open your web application in your favourite desktop browser and check the console and see a log of what is happening. Chrome & Safari (right click, Inspect element, Console), Firefox the same again but you need firebug.

<script type="text/javascript">
var cacheStatusValues = [];
cacheStatusValues[0] = 'uncached';
cacheStatusValues[1] = 'idle';
cacheStatusValues[2] = 'checking';
cacheStatusValues[3] = 'downloading';
cacheStatusValues[4] = 'updateready';
cacheStatusValues[5] = 'obsolete';

var cache = window.applicationCache;
cache.addEventListener('cached', logEvent, false);
cache.addEventListener('checking', logEvent, false);
cache.addEventListener('downloading', logEvent, false);
cache.addEventListener('error', logEvent, false);
cache.addEventListener('noupdate', logEvent, false);
cache.addEventListener('obsolete', logEvent, false);
cache.addEventListener('progress', logEvent, false);
cache.addEventListener('updateready', logEvent, false);

function logEvent(e) {
var online, status, type, message;
online = (navigator.onLine) ? 'yes' : 'no';
status = cacheStatusValues[cache.status];
type = e.type;
message = 'online: ' + online;
message+= ', event: ' + type;
message+= ', status: ' + status;
if (type == 'error' && navigator.onLine) {
message+= ' (prolly a syntax error in manifest)';

console.log('swap cache has been called');

setInterval(function(){cache.update()}, 10000);

Big thanks to Jonathan Stark for the code.

Leave a comment

Your email address will not be published. Required fields are marked *