1 – Add HTML5 doctypeThe first thing to do is create a valid HTML5 document. The HTML5 doctype is easier to remember than ones used for xhtml:
<!DOCTYPE html> <html> ...Create a file named
index.html, or get the example files from my CSS3 media queries article to use as a basis for this tutorial.
In case you need it, the full HTML5 specs are available on the W3C website.
2 – Add .htaccess supportThe file we’re going to create to cache our web page is called a
manifestfile. Before creating it, we first have to add a directive to the
.htaccessfile (assuming your server is Apache).
.htaccessfile, which is located on your website root, and add the following code:
AddType text/cache-manifest .manifestThis directive makes sure that every
.manifestfile is served as text/cache-manifest. If the file isn’t, then the whole manifest will have no effect and the page will not be available offline.
3 – Create the manifest fileNow, things are going to be more interesting as we create a
manifestfile. Create a new file and save it as
offline.manifest. Then, paste the following code in it. I’ll explain it later.
CACHE MANIFEST #This is a comment CACHE index.html style.css image.jpg image-med.jpg image-small.jpg notre-dame.jpgRight now, you have a perfectly working
manifestfile. The way it works is very simple: After the
CACHEdeclaration, you have to list each files you want to make available offline. That’s enough for caching a simple web page like the one from my example, but HTML5 caching has other interesting possibilities.
For example, consider the following
CACHE MANIFEST #This is a comment CACHE index.html style.css NETWORK: search.php login.php FALLBACK: /api offline.htmlLike in the example
manifestfile, we have a
CACHEdeclaration that caches index.html and style.css. But we also have the
NETWORKdeclaration, which is used to specify files that shouldn’t be cached, such as a login page.
The last declaration is
FALLBACK. This declaration allows you to redirect the user to a particular file (in this example,
offline.html) if a resource (/api) isn’t available offline.
4 – Link your manifest file to the html documentNow, both your
manifestfile and your main html document are ready. The only thing you still have to do is to link the
manifestfile to the html document.
Doing this is easy: simply add the
manifestattribute to the
htmlelement as shown below:
5 – Test itOnce done, you’re ready to go. If you visit your
index.htmlfile with Firefox 3.5+, you should see a banner like this one:
Other browser I’ve tested (Chrome, Safari, Android and iPhone) do not warn about the file caching, and the file is automatically cached.
Below you’ll find the browser compatibility of this technique: As usual Internet Explorer does not support it.
- IE: No support
- Firefox: 3.5+
- Safari: 4.0+
- Chrome: 5.0+
- Opera: 10.6+
- iPhone: 2.1+
- Android: 2.0+