One of the exciting new features of HTML5 is the ability to create offline web applications. The idea is that the developer can set up a manifest that tells the browser to cache the application. The latest versions download to your machine when you visit, and if you want to use the application when you’re not connected, you’re automatically directed to the cached version.
Obviously, an offline application isn’t going to be much use for anything server-intensive. You’re not going to be able to book a flight or buy a dvd – at least, not until you’re back online. But it will be useful for more client-side focused apps such as games.
So useful, I want to be able to use it right now.
I’ve mentioned my Chutes/Snakes and Ladders game a few times on this blog. One of my goals with the game was to allow users to create their own personalized versions and embed them in their websites. The problem is – what if they have a popular site and I get hit for a lot of bandwidth?
The data URI scheme allows you to encode a resource such as an image or a sound using base64, and then set the encoded text as the source for the HTML element. It’s a widely supported but little used technique – and it means that instead of resources being stored in separate files, they are included in the HTML file itself. There’s a price to pay, of course. The base64 strings are bigger than the original files, so in normal circumstances, you’re using more bandwidth not less. But it allows you to create an application where all the resources are downloaded to the client – or, in my case, where everything can be included in someone else’s website and I don’t pay for their bandwidth.
Here’s an excerpt from the HTML source for a png image:
<img src=”data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADx/ …” />
It works exactly the same way with HTML5 audio files:
<audio><source id=”drip.ogg” src=”data:application/ogg;base64,T2dnUwACAAAAAAZroL …” />
The key thing is that little bit of meta information at the start of the attribute value. First you specify that you’re using data, not a file reference. Then you tell it the MIME type and the encoding, add a comma and enter your encoded text. Simple. Now all I had to do was write a program convert uploaded game images into base64 strings. The underlying app is a C# ASP.NET MVC application, so that meant writing the following:
The end result is a web application that can be completely downloaded to the client. You can check out the completed game, and the offline versions which you can embed in your own site, at http://lalaladders.time2yak.com/
For related information, check out these courses from Learning Tree: