Introduction Offline access is increasingly important for web-based applications. While all browsers have caching mechanisms, they are unreliable and may not always work as expected. HTML5 uses the ApplicationCache interface to solve some of the problems caused by offline.
Using the cache interface brings the following three advantages to your application:
Offline browsing – users can browse your complete website while offline
Speed – cached resources are local resources , so the loading speed is faster.
Less server load – the browser will only download resources from servers that have changed.
Application Cache (also known as AppCache) allows developers to specify which files the browser should cache for offline users. Even if the user presses the refresh button while offline, your app will load and run normally.
Cache manifest file
A cache manifest file is a simple text file that lists the resources that the browser should cache for offline access.
Refer to the manifest file
To enable application caching for an application, add the manifest attribute to the document's html tag:
...
You should add the manifest attribute on every page of your web application that you want to cache. If a web page does not contain the manifest attribute, the browser will not cache the page (unless the attribute is explicitly listed in the manifest file). This means that every web page that the user browses that contains a manifest will be implicitly added to the application cache. Therefore, you don't need to list every page in your inventory.
The manifest attribute can point to an absolute URL or a relative path, but the absolute URL must have the same origin as the corresponding web application. The manifest file can use any file extension, but must be served with the correct MIME type (see below).
...
Manifest files must be provided as text/cache-manifest MIME type. You may need to add custom file types to your web server or .htaccess configuration.
For example, to provide this MIME type in Apache, add the following line to your configuration file:
AddType text/cache-manifest .appcache To provide this in Google App Engine's app.yaml file MIME type, add the following:
- url: /mystaticdir/(.*.appcache)
static_files: mystaticdir/1
mime_type: text/cache-manifest
upload: mystaticdir/(. *.appcache) manifest file structure
The simple manifest format is as follows:
CACHE MANIFEST
index.html
stylesheet.css
images/logo.png
scripts/main.js The example will cache four files on the web page that specifies this manifest file.
You need to pay attention to the following points:
The CACHE MANIFEST string should be on the first line and is required.
A website’s cached data size must not exceed 5 MB. However, if you're writing an app for the Chrome Web Store, you can use unlimitedStorage to remove this restriction.
If the manifest file or the resources specified in it cannot be downloaded, the entire cache update process will not proceed. In this case, the browser will continue to use the original application cache.
Let's look at a more complex example:
CACHE MANIFEST
# 2010-06-18:v2
# Explicitly cached 'master entries'.
CACHE:
/favicon.ico
index.html
stylesheet.css
images/logo.png
scripts/main.js
# Resources that require the user to be online.
NETWORK:
login.php
/myapi
http://api.twitter.com
# static.html will be served if main.py is inaccessible
# offline.jpg will be served in place of all images in images/large/
# offline.html will be served in place of all other .html files
FALLBACK:
/main.py /static.html
images/large/ images/offline.jpg
*.html /offline.html Lines starting with "#" are comment lines, but can also be used for other purposes. The app cache is only updated when its manifest file changes. For example, if you modify an image resource or change a JavaScript function, those changes will not be recacheed. You must modify the manifest file itself to allow the browser to refresh the cache file. Creating comment lines with generated version numbers, file hashes, or timestamps ensures users have the latest version of your software. You can also programmatically update the cache when a new version becomes available, as described in the Updating the Cache section.
A manifest can include three different sections: CACHE, NETWORK, and FALLBACK.
CACHE:
This is the default part of the entry. Files listed under this header (or the files immediately following CACHE MANIFEST) are explicitly cached the first time they are downloaded.
NETWORK:
The files listed under this section are whitelisted resources that need to be connected to the server. All requests for these resources bypass the cache regardless of whether the user is offline. Wildcard characters can be used.
FALLBACK:
This section is optional and is used to specify a fallback page if the resource cannot be accessed. The first URI represents the resource and the second represents the fallback web page. Both URIs must be related and must have the same origin as the manifest file. Wildcard characters can be used.
Please note: These sections can be arranged in any order, and each section can appear repeatedly in the same list.
The following list defines the "comprehensive" page (offline.html) that is displayed when a user attempts to access the root of the site offline, and also indicates that all other resources (such as those on remote sites) require an Internet connection.
CACHE MANIFEST
# 2010-06-18:v3
# Explicitly cached entries
index.html
css/style.css
# offline.html will be displayed if the user is offline
FALLBACK:
/ /offline.html
# All other resources (e.g. sites) require the user to be online.
NETWORK:
*
# Additional resources to cache
CACHE:
images/logo1.png
images/logo2.png
images/logo3.png Please note: HTML files that reference manifest files will be automatically cached. So you don't need to add it to your list, but we recommend that you do.
Please note: HTTP cache headers and cache limits set on pages served over SSL will be replaced with cache manifests. Therefore, web pages served over https can run offline.
Update cache Apps will remain cached while offline unless one of the following occurs:
A user clears the browser's data storage for your website.
The manifest file has been modified. Note: Updating a file listed in the manifest does not mean that the browser will re-cache the resource. The manifest file itself must be changed.
App cache is updated programmatically.
Cache status The window.applicationCache object provides programmatic access to the browser's application cache. Its status attribute can be used to view the current status of the cache:
var appCache = window.applicationCache;
switch ( appCache.status) {
case appCache.UNCACHED: // UNCACHED == 0
return 'UNCACHED';
break;
case appCache.IDLE: // IDLE == 1
return 'IDLE';
break;
case appCache.CHECKING: // CHECKING == 2
return 'CHECKING';
break;
case appCache.DOWNLOADING: // DOWNLOADING == 3
return 'DOWNLOADING';
break;
case appCache.UPDATEREADY: // UPDATEREADY == 4
return 'UPDATEREADY';
break;
case appCache.OBSOLETE: // OBSOLETE == 5
return 'OBSOLETE';
break;
default:
return 'UKNOWN CACHE STATUS';
break;
};
To update the cache programmatically, first call applicationCache.update(). This operation will attempt to update the user's cache (provided the manifest file has been changed). Finally, when applicationCache.status is in the UPDATEREADY state, call applicationCache.swapCache() to replace the original cache with the new cache.
var appCache = window.applicationCache;
appCache.update(); // Attempt to update the user's cache.
...
if (appCache.status == window.applicationCache.UPDATEREADY) {
appCache.swapCache(); // The fetch was successful, swap in the new cache.
}
Please note: Using update() and swapCache() in this way will not provide the user Updated resources. This process simply lets the browser check for new manifests, download specified updates, and repopulate the app cache. Therefore, the web page needs to be reloaded twice to provide new content to the user, the first time to obtain a new application cache, and the second time to refresh the web page content.
The good news is, you can avoid the hassle of reloading twice. To update users to the latest version of the website, you can set up a listener to listen for the updateready event when the web page is loaded:
// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {
window.applicationCache. addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the new hotness.
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window. location.reload();
}
} else {
// Manifest didn't changed. Nothing new to server.
}
}, false);
}, false );
APPCACHE EVENTS As you might expect, additional events are used to monitor the status of the cache. The browser triggers corresponding events for download progress, application cache updates, error status, etc. The following code snippet sets up event listeners for each cache event type:
function handleCacheEvent(e) {
//...
}
function handleCacheError(e) {
alert('Error: Cache failed to update!');
};
// Fired after the first cache of the manifest.
appCache.addEventListener('cached', handleCacheEvent, false);
// Checking for an update. Always the first event fired in the sequence.
appCache.addEventListener('checking', handleCacheEvent, false);
// An update was found. The browser is fetching resources.
appCache.addEventListener('downloading', handleCacheEvent, false);
// The manifest returns 404 or 410, the download failed,
// or the manifest changed while the download was in progress.
appCache.addEventListener('error', handleCacheError, false);
// Fired after the first download of the manifest.
appCache.addEventListener('noupdate', handleCacheEvent, false);
// Fired if the manifest file returns a 404 or 410.
// This results in the application cache being deleted.
appCache.addEventListener('obsolete', handleCacheEvent, false);
// Fired for each resource listed in the manifest as it is being fetched.
appCache.addEventListener('progress', handleCacheEvent, false);
// Fired when the manifest resources have been newly redownloaded.
appCache.addEventListener('updateready', handleCacheEvent, false);
如果清单文件或其中指定的资源无法下载,整个更新都将失败。在这种情况下,浏览器将继续使用原应用缓存