Web app guide for building HTML5 offline applications

Source: Internet
Author: User

When creating a web app running on a mobile phone, we need to consider the offline usage of the user in view of the Network Situation of the mobile phone user.

HTML5 supports building offline applications. Using its local cache mechanism, You Can cache all the resource files required by the application to the local, so that the application can be used offline. The first thing to note is that the local cache is different from the webpage cache of the drive browser. The webpage cache is based on the webpage, that is, the content of a webpage is cached, rather than the whole app. At the same time, the webpage cache is not reliable. We do not know which page of our app has been cached, which resources of the page have been cached, and the local cache is completely controllable for the cached content.

Using offline caching not only enables applications to be used offline, but also effectively speeds up webpage loading (local data is naturally faster ), at the same time, the server load is reduced (only the updated content needs to be downloaded ).

As mentioned earlier, the local cache can specify the content to be cached, which is implemented by configuring manifest. You can configure manifest for the entire app or a single page.

The simple manifest format is as follows:

CACHE MANIFESTindex.htmlstylesheet.cssimages/logo.pngscripts/main.js

The first line of the file must be cache manifest.

The manifest declares the HTML pages, CSS, images, and JS files to be cached.

Let's look at a complicated manifest file:

Cache manifest # specify a version number # version 1 # This category specifies the resource file cache to be cached:/favicon.icoindex.htmlstylesheet.css images/logo.png scripts/main. JS # specify the resource file Network: login. phphttp: // foocoder.com # specify two files in each row. The first is the resources used online, and the second is the resources used offline. Fallback:/main. PY/static.html images/large/images/offline.jpg *. html/offline.html

Note is started. Because the manifest file is updated only when it changes, we can add a version number to facilitate control.

The file contains three categories:

The cache category specifies the resource files to be cached.

The network type specifies the resource files that are not cached, that is, they can be accessed only when the network is connected.

Each fallback row specifies two files. The first is the resource used online, and the second is the standby resource used offline. Here, * is a wildcard, which uses all the. html files in line.

After configuring the manifest file, we only need to reference it on the page. Specify the address of the manifest file under the manifest attribute of the HTML tag as follows:

This address can be either an absolute address or a relative address, but the MIME type of the file must be text/cache-manifest, so you need to configure the server to add support for this type, for example, for the Apache server, you need to configure mime. add the following content to types:

AddType text/cache-manifest .manifest

By now, the basic offline cache content has been completed. When the manifest file changes, the browser checks the manifest file and updates the cache.

We have to consider a question: how does the browser handle local cache? After the server updates the application, will the user use the latest resources when opening the application? The answer is no. This requires understanding the entire interaction process between the browser and the server when offline caching is used.

1. First access

At the first time, there was no special issue. The browser called index.html to request all resource files. Then the manifest file will be processed to request all the resource files in the manifest. Note that even if you have already requested all the resource files, the request must be repeated here. Finally, these files are cached locally.

2. Access again

When you try again, the browser finds that there is a local cache, so it loads the local cache content. Request the manifest file from the server. If the manifest file is not updated, code 304 is returned, and the browser will not process it. If the manifest has been updated, request the resource files in all manifest and cache them again.

Therefore, even if the server updates manifest and other resources, the user can open the previous page. You must re-open the resource to use the updated resource.

Is there a way to update the cache immediately? Yes. We can use the applicationcache object to do this. However, it is only possible to update the cache immediately. It still takes effect after the user opens the cache again. Next, let's take a look at how to use the applicationcache object to immediately update the cache.

Window. applicationcache has a status attribute. You can know the current cache status through it

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;};

Now that the status can be obtained, we only need to request updates and then update the cache when the status is appcache. updateready.

The applicationcache. Update () method attempts to update the user cache, while the applicationcache. swapcache () method updates the local cache:

VaR appcache = Window. applicationcache; appcache. update (); // start to update if (appcache. status = Window. applicationcache. updateready) {appcache. swapcache (); // update cache}

As mentioned earlier, even if the cache is updated, you still need to reload to use the latest resources. In this case, you can be prompted to update the resource. You only need to listen to the onupdateready event, which starts after the cache is downloaded to the local device, so that you can prompt the user at this time:

Window. addeventlistener ('load', function (e) {window. applicationcache. addeventlistener ('updateready', function (e) {If (window. applicationcache. status = Window. applicationcache. updateready) {// update the local cache window. applicationcache. swapcache (); If (confirm ('has a new version. Do you want to switch to the latest version immediately? ') {Window. Location. Reload () ;}} else {}}, false) ;}, false );

The applicationcache object also provides other events:

Onchecking, onerror, onnoupdate, ondownloading, onprogress, onupdateready, oncached and onobsolete

During the interaction between the browser and the server, all errors start with an error event, which can be handled by listening to the error event:

var appCache = window.applicationCache; appCache.addEventListener('error', handleCacheError, false); function handleCacheError(e) {  alert('Error: Cache failed to update!');};

You are welcome to leave a message.

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.