HTML5 Offline Application

Source: Internet
Author: User
Tags browser cache

Recently, finishing a bit about H5 offline application cache knowledge, rest at home today, and share with you, I hope the big study and work, can be helpful.

HTML5 's offline web App allows us to interact with the site while offline. This is useful for improving the speed of website access and making a Web-off application (such as a HTML5 game).

First, what is the offline Web application? Why develop an offline Web application?

Offline Web application means that when the client is not connected locally to the server of the Web application, the Web application is used locally on the client to do the work.

Web applications have become increasingly complex, and many areas are leveraging Web applications. However, it has a fatal disadvantage: If a user does not have a connection to the Internet, he cannot take advantage of the Web application. So H5 has added an API that solves this problem with a local caching mechanism, making it possible to develop an offline application.

To make the Web application work when it is offline, you must put all the resource files that make up the Web application, such as HTML files, CSS files, JavaScript script files, etc. in the local cache, and when the server is not connected to the Internet, You can also run the Web application properly with resource files from the local cache.

second, what is the local cache, the difference between the local cache and the browser page cache

There are significant differences between a Web application's local cache and a browser's page cache.

1. The local cache serves the entire Web application, and the browser's page cache serves only a single page. Any Web page has a Web cache. The locally cached pages are cached to those specified caches.

2. Web caching makes insecure and unreliable, because we don't know exactly which pages are cached on the site, and what resources are cached on the page. While the local cache is reliable, we can control what content is cached, what is not cached, and developers can use programmatic means to control cached updates, exploiting the various properties, states, and events of the cached object to develop more powerful offline applications.

3. (some) the browser will proactively save its own cache files to speed up website loading. But to implement a browser cache must satisfy the premise that the network must remain connected. If the network is not connected, the site cannot be opened even if the browser has enabled caching for a site. You will only receive an error message. Using an offline Web application, we can proactively tell the browser which files should be fetched or cached from the Web server and still be able to access the site while the network is offline.

Third, how to implement HTML5 application cache ? What is a manifest file, what is in the file that needs to be cached locally, and what is not needed?

Implementing the HTML5 application cache is as simple as three steps and does not require any APIs. Just tell the browser that you need to cache the files offline and make some simple settings for the server and the Web page.

• Create a cache.manifest file and make sure the file has the correct content
• Set the content type on the server
• all HTML files point to cache.manifest
First: Create a manifest file

The local cache of the Web application is managed by the manifest file for each page, and the manifest file is a simple text file that lists the file names of the resource files that need to be cached or not to be cached, as well as the access paths to those resource files, in the form of a manifest. You can specify a single manifest file for each page, or you can create a total manifest file for the entire Web application. The following is an example of a detailed description of the manifest file: (the file is a manifest file for the Hello.html Web page)

In the manifest file,

    1. The first line must be the "cache dmanifest" text to inform the browser of the role of this file, which is to specify the resource files in the local cache.

2. in the manifest file, annotations may be added to the necessary explanations or explanations. Comment lines begin with a "#" literal.

    1. In the manifest file, you can add a version number to represent the version of this manifest file. The version number can be any form, such as the above "version201011211108", update the manifest file will generally also update the version number. ( The browser does not update the app cache until the Cache.manifest file changes.) If you want to change the cache resource, you must modify the contents of this file at the same time so that the browser knows that they need to update the cache. You can make any changes to the manifest file, but everyone agrees that the best practice is to fix the version number )

4. Specify the resource file, the file path can be a relative path, or it can be an absolute path, when specified, each resource file is a row. When you specify a resource file, you can divide the resource file into three categories, namely, CACHE,NETWORK,FALLBACK.

1) Specify the local resource file that needs to be cached in the cache category. When you specify a resource file that requires a local cache for a page, you do not need to specify the page itself in the cache category, because if a page has a manifest file, The browser will automatically cache the page locally.

2) The NETWORK category displays resource files that specify no local cache, which can only be accessed when the client establishes a connection with the server. This example "*" In this category is a wildcard character, indicating that no resource file specified in this manifest file is cached locally

3) specify two resource files in each row in the FALLBACK category, the first resource file is the resource file that is available for online access, and the second resource file is an alternate resource file that is not available for online access.

Each of these three categories is optional, but if you write the resource file directly at the beginning of the file without specifying a category, the browser treats the resource files as the CACHE category until you see the first category in the file that is written. Allows the same category to be written repeatedly in the same manifest file.

Second: Set the content type on the server

Really run or test offline webapplication, you need to configure the server to allow the server to supporttext/cache-manifestthisMIMEtype (inh5stipulated inManifestof the fileMIMEtype istext/cache-manifest). For example, toApachewhen the server is configured, you need to find the {Apache_home}/conf/mime.typeThis file(. htaccess)and Add the following code at the end of the file:text/cache-manifest. manifest. In Microsoft'sIISthe steps in the server are as follows:

1) Right-click the Default Web site or add a type of Web site, pop-up Properties dialog box

2) Select the "HTTP headers " tab

3) under MIME Mapping, click the File Type button

4) in the open MIME Type dialog box, click the New button

5) Enter "manifest" in the associated extension text, enter "Text/cache-manifest" in the Content Type text box, and click the OK button.

Finally, point the HML page to the manifest file

We need to html html element manifest web All steps for offline caching. Because the contents of the browsed files are not changed and stored locally, the Web page is now opened faster (even in the online state).
Issues to be aware of:

• Each HTML page of the site must have the manifest attribute set for the HTML element . Be sure to do so;
• there can only be one cache.manifest file in your entire site application (recommended in the root directory of the website);
• some browsers (such as ie8-) do not support HTML5 offline caching;

Iv. mastering Applicationcache objects and their properties and events for local caching

Cached Updates

When a Web application is loaded from the cache, all associated files are also fetched directly from the cache. In the online state, the browser asynchronously checks to see if the manifest file is updated. If there is an update, the new manifest file and all the files listed in the manifest will be downloaded and saved to the program cache. However, be aware that the browser simply checks the manifest file without checking that the cached file is updated: Only the manifest file manifest file is checked.

If you modify a cached JS file, and you want the file to take effect, you must update the following manifest file. Since the list of files that the application relies on doesn't actually change, the simplest way is to update the version s

Chche MANIFEST

CACHE:

#MyApp version 1 (change this number for the browser to download again)

Myapp.html

Myapp.css

Myapp.js

The same "unload" is required to delete the manifest file on the server side, which returns 404 when the file is requested, and modifies the HTML file so that they "unlink" it from the list.

Note: The browser checks the manifest file and updates the cached operation asynchronously, possibly before loading the app from the cache, or at the same time. So for a simple Web application, after updating the manifest file, the user must load the app two times to ensure that the latest version takes effect: The first time is to load the old version from the cache and then update the cache; the second is to load the latest version from the cache.

The browser triggers a sequence of events during the update of the cache, which can be tracked by the registration handler to provide feedback to the user.

Such as:

Applicationcache.onupdateready= function () {

var reload = confirm ("A new version of this application is available\n and would be used the next time you reload.\n");

if (reload) location.reload ();

}

The event is registered on the Applicationcache object, which is the value of the window's Applicationcache property. Browsers that support application caching define this property.

Every time the application loads, it checks the manifest file

The "Checking" event is always triggered first.

Window. applicationcache.onchecking = function () {

Status ("Checking for a new version.");

return false;

}

If no changes are made, the application is already cached

The "Noupdate" event is triggered and the whole process is over.

Window.applicationCache.onnoupdate = function () {

}

If the application has not been cached, or if the manifest file has changed

Then the browser downloads and caches all the resources in the list

Triggering the "Downloading" event, which also means that the download process starts

Window. applicationcache.ondownloading = function () {

Status ("Downloading new version manifest");

Window.progresscount = 0;

return false;

}

The "Progress" event is intermittently triggered during the download process

Usually when each file is downloaded

window.applicationCache.onprogress = function (e) {}

When the download is complete and the application is downloaded to the cache for the first time, the browser triggers a "cached" event

window.applicationCache.oncached = function (e) {

Status ("ThisApplication is now cached locally");

return false;

}

When the download is complete and the application in the cache is updated, the browser triggers the "Updaterady" event

Note that when this event is triggered, the user can still see the old version of the application

Window.applicationCache.onupdateready = function (e) {

Status ("Anew version has been downloaded. Reload to run it ");

return false;

}

If the browser is offline and the checklist list fails, an "error" event is triggered

This event is also triggered when an application that is not cached references a manifest file that does not exist

Window.applicationCache.onerror = function (e) {

Status ("Couldn ' tload manifest or Cache application");

return false;

}

If a cached application references a nonexistent manifest file, "obsolete" is triggered

When the app is removed from the cache, the resource is not loaded from the cache but over the network

Window.applicationCache.onobsolete = function (e) {

Status ("ThisApplication is no longer cached. Reload to get the latest version from Thenetwork. ");

return false;

}

6 Possible property values for Applicationcache.status

N applicationcache.uncached (0)

The application does not have the manifest property set: Not Cached

n Applicationcache.idle (1)

The manifest file has been checked and the latest application has been cached

n applicationcache.checking (2)

The browser is checking the manifest file

n applicationcache.downloading (3)

The browser is downloading and caching all the files listed in the list

n Applicationcache.updateready (4)

The latest version of the app has been downloaded and cached

n Applicationcache.obsolete (5)

The manifest file does not exist and the cache is cleared

Fivethe Applicationcache object also defines two methods of update () and Swapcache ()

N Update

The update cache algorithm is explicitly called to detect whether the latest version of the application is available. This causes the browser to detect the same manifest file (and trigger the same event), which is the same as when loading the application for the first time.

N SwapCache

It tells the browser to discard the old cache, and all requests are taken from the new cache. Note that this does not reload the application: all the loaded HTML files, pictures, scripts, and so on are not changed. However, subsequent requests are taken from the most recent cache. This can cause "version confusion" issues, so it is generally not recommended unless the application is well designed to ensure that this is not a problem. It makes sense to call SwapCache () only when Applicationcache.updateready and Applicationcache.absolete (when the state obsolete, call it to immediately discard the discarded cache, Allow all subsequent requests to be acquired over the network). If the Swapcache () method is called when the state attribute is a different value, it throws an exception.

Six, how to determine the online or offline status?

An offline web App is a program that installs itself in the application cache so that it can be accessed even when the browser is offline. In order to be available offline, Web applications need to be able to tell others whether they are offline or online and "perceive" when the state of the network connection changes. With the Navigator.online property, Navigator.online is HTML5 defined to detect whether the device is online or offline. The corresponding value is False or true.

But the performance of different browsers is inconsistent.

    • IE 6+ and Safari 5+ are able to correctly detect that the network has been disconnected and set Navigator.online to Flase.
    • Firefox and opera 10.6+ also support Navigator.online. However, you need to manually say that the browser is set to offline mode for your browser to function.
    • Chrome 11 and later always set Navigator.online to true. (But the author's Chrome 21 is already working.)

HTML5 defines the Online&offline event for monitoring network state changes.

Window.addeventlistener (' online ', callback); Offline to Online

Window.addeventlistener (' Offline ', callback); Online to Offline

Currently, in addition to IE (ie only supports the Navigator.online attribute), this event is supported by the latest browsers.

HTML5 Offline Application

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.