Saturday, August 17, 2013

Automatically building a cache manifest file

HTML5 has the capability to work offline and it allows you to cache files of your application on the browser by using a cache manifest. The question is, which files to cache?

Simple applications, with an HTML file, a couple of JS and CSS files are not a problem. But as soon as you move to more complex applications, the number of files explodes - think imported CSS files, background images, images within your page, etc. So here's a little help to build your cache file!

1. Start by getting the offlineHelpers.js file and put it on your website. It's easier if you put it on the folder of the page you want to cache, but you can put it anywhere. If you don't have a site yet, download the whole project and play with the provided test.html file.

2. Be sure the page you want to cache includes jQuery. This is only needed to run the offlineHelpers script, you can remove it afterwards. You don't even need to download it, just src the script from here: http://code.jquery.com/jquery-1.10.1.min.js

3. Launch chrome (yes, for now it only works on chrome). Load the offllineHelpers script by opening the console (cmd+alt+j on the Mac) and typing $.getScript('offlineHelpers.js'). Next, call offlineHelpers.getCacheFile() on the console.

4. Calling getCacheFile should result on a bunch of debug lines (in gray) followed by your cache manifest file. Something like:

Getting stylesheets
Found an import: jumbotron-responsive.css
Getting JS files
Getting Image files
CACHE MANIFEST

# CSS Files
css/bootstrap.css
img/glyphicons-halflings.png
img/glyphicons-halflings-white.png
css/jumbotron-narrow.css
css/jumbotron-responsive.css

# Javascript Files
http://code.jquery.com/jquery-1.10.1.min.js

# Image Files
img/creatures.jpg

Next, tweak the result and copy to your cache.manifest file.

Let me know how this worked for you! If the script missed a file, let me know on the comments and I'll try to fix it!

No comments: