HTML5 uses the ApplicationCache interface to implement offline caching technology to solve offline Problems

Source: Internet
Author: User

Comments: Offline access is more and more important for network-based applications. Although all browsers have cache mechanisms, they are not reliable. HTML5 uses the ApplicationCache interface to solve some problems brought about by offline access, for more information, seeIntroduction
Offline access is increasingly important for network-based applications. Although all browsers have cache mechanisms, they are not reliable and may not always play the expected role. HTML5 uses the ApplicationCache interface to solve some of the problems brought about offline.
Using the cache interface can bring the following three advantages to your application::
Offline browsing-users can browse your entire website offline
Speed-Cache resources are local resources, so the loading speed is faster.
Less server load-the browser only downloads resources from the changed server.

Application cache (also known as AppCache) allows developers to specify which files should be cached in the browser for access by offline users. Even if you press the refresh button offline, your application will load and run normally.
Cache List Files
The cache list file is a simple text file that lists the resources that the browser should cache for offline access.
Reference the inventory file
To enable application caching for an application, add the manifest attribute to the html tag of the document:

The Code is as follows:
<Html manifest = "example. appcache">
...
</Html>

You should add the manifest attribute to each page of the network application to be cached. If the webpage does not contain the manifest attribute, the browser will not cache the webpage (unless the attribute is explicitly listed in the inventory file ). This means that every page containing manifest browsed by the user is implicitly added to the application cache. Therefore, you do not need to list each web page in the list.
The manifest attribute can point to the absolute URL or relative path, but the absolute URL must be the same as the corresponding network application. Configuration files can use any file extension, but must be provided in the correct MIME type (see below ).

The Code is as follows:
<Html manifest = "http://www.example.com/example.mf">
...
</Html>

The configuration file must be of the text/cache-manifest MIME type. You may need to add a custom file type to the network server or. htaccess configuration.
For example, to provide this MIME type in Apache, add the following line in your configuration file:
AddType text/cache-manifest. appcache to provide this MIME type in the App. yaml file of Google app Engine, add the following content:
-Url:/mystaticdir/(. * \. appcache)
Static_files: mystaticdir/\ 1
Mime_type: text/cache-manifest
Upload: mystaticdir/(. * \. appcache) file structure
The simple configuration format is as follows:
CACHE MANIFEST
Index.html
Stylesheet.css
Images/logo.png
Scripts/main. js this example caches four files on the webpage of the specified list file.
Note the following:
The cache manifest string must be in the first line and is required.
The cache data volume of the website cannot exceed 5 MB. However, if you want to write applications for Chrome online app stores, you can use unlimitedStorage to cancel this restriction.
If the configuration file or the specified resource cannot be downloaded, the entire cache update process cannot be performed. In this case, the browser will continue to use the original application cache.
Let's take a look at more complex examples:
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
*. Lines starting with "#" in html/offline.html are comments, but can also be used for other purposes. The application cache is updated only when its configuration file is changed. For example, if you modify image resources or modify JavaScript Functions, these changes will not be cached again. You must modify the inventory file to allow the browser to refresh the cached file. Use the generated version number, file hash value, or timestamp to create a comment line. This ensures that you get the latest version of your software. You can also update the cache programmatically after a new version appears, as described in the update cache section.
The configuration includes the following three parts: CACHE, NETWORK, and FALLBACK.
CACHE:
This is the default part of the entry. The system will explicitly CACHE the files listed under this header after the first download (or files followed by the cache manifest.
NETWORK:
The files listed in this section are the whitelist resources that need to be connected to the server. No matter whether the user is offline or not, all requests to these resources will bypass the cache. Wildcard characters can be used.
FALLBACK:
This part is optional and is used to specify the backup webpage when the resource cannot be accessed. The first URI indicates the resource, and the second URI indicates the backup web page. The two Uris must be related and must be the same as the configuration file. Wildcard characters can be used.
Note: These parts can be arranged in any order, and each part can be repeated in the same list.
The following list defines the "Comprehensive" Web page (offline.html) displayed when you attempt to access the root of the website offline. It also indicates that all other resources (such as resources on a remote website) Require 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 note: the system automatically caches HTML files that reference the list file. Therefore, you do not need to add it to the list, but we recommend that you do so.
Note:: The HTTP cache header and the cache restrictions set for Web pages provided through SSL will be replaced with the cache list. Therefore, the web pages provided by https can run offline.

Update Cache
The application remains cached after going offline, unless the following situations occur:
The user clears the data storage of your website by the browser.
The configuration file has been modified. Note: updating a file listed in the List does not mean that the browser will cache the resource again. The configuration file must be changed.
The application cache is updated programmatically.

Cache status
Window. applicationCache object is a programming access method for browser application cache. Its status attribute can be used to view the current status of the cache:

The Code is as follows:
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, call applicationCache. update () first (). This operation will attempt to update the user's cache (provided that the configuration file has been changed ). Finally, when applicationCache. status is in the UPDATEREADY status, call applicationCache. swapCache () to replace the original cache with the new cache.

The Code is as follows:
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.
}

Note:: Using update () and swapCache () in this way will not provide users with updated resources. This process only allows the browser to check for a new list, download the specified update content, and refill the application cache. Therefore, you must reload the webpage twice to provide new content to the user. The first is to obtain the new application cache, and the second is to refresh the webpage content.
The good news is that you can avoid the trouble of reloading twice. To update a user to the latest website version, you can set a listener to listen to the updateready event when the webpage is loaded:

The Code is as follows:
// 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 event
As expected, additional events are used to monitor the cache status. The browser triggers events such as the download progress, application cache update, and error status. The following code snippet sets an event listener for each cache event type:

The Code is as follows:
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/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 );

If the configuration file or the specified resource cannot be downloaded, the entire update will fail. In this case, the browser will continue to use the original application Cache

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.