Generate offline.manifest with every Java build
Introduction
In this post I will explain how to automatically generate a list of web resources for HTML5 offline caching. To keep the story short, you need to specify all CSS, JS, etc. in a manifest file. Then the browser will know that it needs to store them in cache. When you disconnect from the Internet, it will use those files instead of complaining about no connection available.
Project structure
Lets assume you're using Maven and your project structure looks something like this:
index.html
To enable offline mode every html file of your website needs to include offline manifest. For example this is how index.html would look:
offline.manifest
offline.manifest looks something like this:
It is a good practice to add some form of a timestamp during every build (# 01/08/2013 16:00:00). By doing this you let the browser know that it needs to reload the cached resources. Otherwise, if one of your files changes, but it is not a new file and the name haven't changed, there is a good chance it won't be reloaded.
We could add files manually to the offline.manifest, but that's quite error-prone. You can easily forget to add a file and then the offline mode won't work in a particular case. It's usually better to automatically generate it. Here we will use Apache Ant. The script logic will be placed in the build.xml.
build.xml
If you execute ant from the project directory:
it will automatically execute the generate-offline-manifest target:
pom.xml
In order to generate the offline.manifest every time the .war file is created, you can invoke the build.xml in your Maven build, during the prepare-package phase. You can accomplish this by adding the following snippet to your pom.xml:
The End
I hope you found this micro-tutorial useful. Happy coding!