HTML5In developing an HTML5 offline app, a cache manifest is required in order to tell the app which files to cache.  If a file changes, the manifest file needs to be changed as well.  If a file is added, it needs to be added to the manifest.  During the development process this can be quite a PITA.

Enter the dynamic cache manifest.  Not only does this handle all the file adds/deletes, but it also handles changed files as it generates an MD5 hash of all files which it stores in the manifest file.  So if the hash changes, the manifest changes.

Note that this was written in PHP.  If you’re using ASP or some other server-side technology you’ll need to adapt this.

// Add the correct Content-Type for the cache manifest
header('Content-Type: text/cache-manifest');

// Write the first line

// Initialize the $hashes string
$hashes = "";

$dir = new RecursiveDirectoryIterator(".");

// Iterate through all the files/folders in the current directory
foreach(new RecursiveIteratorIterator($dir) as $file) {
	$info = pathinfo($file);
	// If the object is a file
	// and it's not called manifest.php (this file),
	// and it's not a dotfile, add it to the list
	if ($file->IsFile()
		&& $file != "./manifest.php"
		&& substr($file->getFilename(), 0, 1) != ".")
		// Replace spaces with %20 or it will break
		echo str_replace(' ', '%20', $file) . "n";
		// Add this file's hash to the $hashes string
		$hashes .= md5_file($file);

// Hash the $hashes string and output
echo "# Hash: " . md5($hashes) . "n";

Then in your html file you just add a reference to manifest.php:

<!DOCTYPE html>

<html manifest="manifest.php">

Once you’ve got this core structure down you can add logic for NETWORK, FALLBACK or CACHE sections as you see fit.  The other great thing about this approach is that you don’t need to add a text/cache-manifest MIME type to your server configuration / .htaccess.  The PHP handles it for you automatically.

Note that I didn’t come up with this on my own, but I use it (or a variation) in all my offline apps. The concept/code was originally published in Building iPhone Apps with HTML, CSS, and JavaScript: Making App Store Apps Without Objective-C or Cocoa, an excellent O’Reilly book which has now made its way online.