Offline Application API
The HTML5 Specification includes an API for creating offline applications. The purpose is two-fold:
- Allow users to access your web application when they are offline.
- Make your web applications faster by taking advantage of local caching.
There are 3 steps involved in turning a regular HTML page into an offline application:
- Create a cache manifest file.
- Reference the cache manifest file in your HTML5 document.
Cache Manifest File
The cache manifest file is a plain text file with a .manifest extension. It is structured as follows:
#Use pound signs for comments
#Explicitly cached entries.
#Fallback files (use only when can't access online files)
Note that you must configure your web server to deliver .manifest files using the "text/cache-manifest" mime type.
In Apache, you can use AddType text/cache-manifest .manifest
In IIS, you can add Mime types through Computer Management.
The HTML File
Referencing the manifest file in your HTML document is easy:
You access the application cache through the window.applicationCache object. It includes a status property indicating the current state of the cache. As the status changes, the following events are fired:
You can catch these events using event listeners: window.applicationCache.addEventListener("error", fnCall, false);.
A Sample Application
Before testing this, be sure to clear your browser's cache first, then take a look at our sample application files below:
And here are the two images, the first of which is shown if the browser can connect to the site:
To test this application, you must access it through a web server (e.g., localhost). Here's how it works:
- The first time you visit the page, all the files will download from the server and get cached:
- Refresh the browser:
- Modify the CSS document (e.g., change the background color) and refresh. Nothing changes. All the files were fed from cache.
- Modify the cache manifest file to force it to be redownloaded (e.g., change the version comment from version 1.0 to version 1.1. Refresh the browser: Notice that the resources are being fetched again, but the page has not updated.
- If you press Cancel on the confirm dialog, the page will not update. Instead, press OK to get the page to update:
- Our manifest file indicates that offline.gif should be displayed if the browser is offline. To see this, you need to go offline, which is hard to do when you're working locally. Note that, if you are able to view the page while offline, the "error" event listener (in script.js) will generate an alert popup, since the page won't be able to fetch the manifest.