This article is to introduce the characteristics of the HTML5 Offline Network application, the actual name of the offline Web application in the World Network is "Offline Web applications", also known as offline caching. When the user opens the browser, the browser downloads and stores the resources specified in a list locally. The next time the user accesses the network program, the browser automatically references the corresponding file in the local cache and no longer downloads the resources from the network. Regardless of whether the offline Web application is designed for Web apps, this is a very useful feature for Web apps, which makes web apps a significant disadvantage to native apps-highly dependent on the network, which can be greatly slowed down. Developers can use this feature to cache elements from web apps to the local side, so that Web apps can work offline, and even Apps that need to work online can cache portions of files to the local side and reduce bandwidth usage, which makes web apps more advantageous than native apps. This feature is now formally introduced below.
I. Offline Network application Basics
The core of an offline network application is a text file with content type Cache-manifest. This file holds files (HTML, CSS, JavaScript, images, etc.) that need to be stored offline in the application. To give a simple example, an application consists of the following files:
- Index.html
- Demo.css
- Demo.js
- Logo.png
Index.html is the home page, other files are referenced in the home page, and if we need to cache the application offline, we need to add a manifest file under Index.html's sibling directory and name the. manifest suffix file, and the contents of the file can be written like this:
12345 |
CACHE MANIFEST ./index.html ./demo.css ./demo.js ./logo.png |
As you can see, the path to the above file is relative to the path, which is relative to the manifest file. Of course, you can also use absolute paths, which does not affect the use of manifest.
Manifest files are easy to write, but there are a few steps to enabling offline caching. The first is the need to associate the manifest file with the application, which is to point the page to the cache list by specifying the manifest value for the HTML tag, for example:
1 |
< html manifest = "demo.manifest" > |
Where demo.manifest is the manifest list file written in the example.
Tip: If you have multiple pages in your application, each page needs to be associated with manifest.
Next, the developer must specify the Text/cache-manifest content type for the manifest file so that the browser can recognize it. For specific methods, if your server supports. htaccess, you can write the following statement in. htaccess:
1 |
AddType text/cache-manifest .manifest |
This can be done by associating the MIME type of the text/cache-manifest with the. manifest file. Of course, the developer may not have the. htaccess permission to write, but in fact, developers can use a few more practical ways to achieve the goal. Because in the actual project development, the number of files in the application will not just like the only 4 in the example above, if there are many files need to cache, each file need to write manifest file manually is quite time-consuming, more troublesome, each change these files must change the manifest file accordingly, So Kayo more recommend that developers use background script directly to get the files that need to be cached and write a manifest list, Kayo familiar background script is PHP, in PHP, you can set the MIME type directly in the code, so you do not need to configure the WEB service to complete the Manife ST's support. As for how to use PHP to write manifest, it will be described in detail below.
Two. Browser support
With regard to offline Web applications that have been fully supported in modern browsers, IE is not supported at all. Specific as follows:
Chrome 4+, Firefox 3.5+, Safari 4+ and Opera 10.6+
Three. White List
By default, the developer will specify the cache for all the files in the application, but in fact there are still some resources that might need to be forced to cancel the cache, that is, the network resources must be accessed and the resource is not available offline. Forcing an element to cancel the cache can use the keyword NETWORK in the manifest file:. Add a list of files under the NETWORK: keyword, which forces the cache to be canceled, and this file list is called a whitelist (Whitelist). In fact, there is also a keyword for the resource that needs to be cached, which is EXPLICIT:, but if no keyword is added at the beginning of all resource lists, the default is considered to be under the list of EXPLICIT: keywords, so the list of resources that need to be cached can be ignored without the Write keyword (as in the example above).
For example, to extend the example above and add logo.png to the whitelist, you can write a manifest file like this.
1234567 |
CACHE MANIFEST ./index.html ./demo.css ./demo.js NETWORK: ./logo.png |
Four. Alternative list
The alternative list is a whitelist supplement, in the whitelist, when there is no Internet connection, the resource cannot be loaded, which will cause the page error, as in the above example, "Logo.png" is set to whitelist, if the user browses the application offline, a corrupted picture link appears, in order to avoid this situation, you can use FALLBACK: Specify an alternative list, the alternative list needs to prepare two files for a resource, if the normal network, will refer to the first file, offline refers to the second file, on this feature, there is a very useful application-indicating whether the program is offline or networked work, It is easy to indicate the status by referencing different pictures in different states. Next Kayo continues to expand the example above, specifying an alternate picture Backup.png for logo.png when offline.
1234567 |
CACHE MANIFEST ./index.html ./demo.css ./demo.js FALLBACK: ./logo.png ./backup.png |
Five. Update manifest
It seems that the application's offline cache has worked well after the three steps above. But there is one important question to note--based on how offline caching works, when the user first uses the application, the browser will download the specified resource according to the list in the manifest file, and the browser will automatically load a copy of those resources the next time the application is used, if the developer modifies the program , the browser will still load the local resources, so we need to give the browser a hint that the program has been updated.
So when does the browser update the local cache?
Only files that are designated to be cached offline in manifest will be re-downloaded by the browser when manifest is modified. The detection of whether the manifest has been modified is to compare the contents of the manifest file by character, including comments and blank lines. Of course, most of the time, the modification of the program will not affect the main file, so the list of files in manifest will not change, so you need to change manifest to inform the browser program has been updated the best way is to modify the comments, developers can add a line of comments in the manifest file, For example, the version number of the program, when the program is updated to modify the version number in the manifest file, the browser will determine that the program has been updated to automatically re-download all the resources that require offline caching. For example, change the example above to:
12345678 |
CACHE MANIFEST # version 1.0 ./index.html ./demo.css ./demo.js FALLBACK: ./logo.png ./backup.png |
It is important to note that "CACHE MANIFEST" is a necessary line and must be the first line in the MANIFEST file. In this way, the next time you change the program and modify the manifest version number, the browser can determine the program update.
Manually update the cache
Of course, in order to have more precise control over the update process, it is best to update the cache using manual methods, and the Offline Network Application Specification also provides the appropriate method for manually updating the cache. Developers can use the Window.applicationCache.update () method to manually update the cache, in order to more accurately determine whether the need for updates, developers can first detect the value of Window.applicationCache.status, if its value is " Updateready "(that is, the browser detects that manifest has been modified), you can call the Window.applicationCache.update () method to update the cache. For example:
123 |
if ( window.applicationCache.status == window.applicationCache.UPDATEREADY ){ window.applicationCache.update(); } |
Six. Writing manifest files using PHP scripts
As mentioned above, scripting the manifest file can also resolve the manifest file extension associated with the MIME type and automatically list the cache files. The specific writing is as follows:
123456789101112131415161718192021222324 |
header(
‘Content-Type: text/cache-manifest‘
);
echo "CACHE MANIFEST\n"
;
$allHashes =
""
;
// 创建一个字符串保存文件的 md5 值
$dir =
new RecursiveDirectoryIterator(
"."
);
foreach
(
new RecursiveIteratorIterator(
$dir
)
as $file
){
// 获取当前目录并遍历文件
if
(
$file
->IsFile() &&
// 判断获取内容为文件
$file
->getFilename() !=
"manifest.php" &&
// "manifest.php" 不缓存
$file
->getFilename() !=
"logo.png" &&
// 备选资源不缓存
$file
->getFilename() !=
"offline.png" &&
!
strpos
(
$file
,
‘/.‘ ) &&
substr
(
$file
->getFilename(), 0, 1 ) !=
"."
){
echo "./" .
$file
->getFilename() .
"\n"
;
$allHashes .= md5_file(
$file
);
// 把每一个缓存的文件的 md5 值连接起来
}
}
echo "FALLBACK:\n"
;
// 输出备选名单
echo "./logo.png ./offline.png\n"
;
echo "# " . md5(
$allHases
) .
"\n"
;
// 把连接起来的 md5 值重新计算一个 md5(因为连接所得的字符串过于冗长)
|
In this script, the directory of the application is obtained and the files in the directory are added to the cache list one by one, and the files such as "manifest.php" and alternative resources are excluded in this process, and the MD5 value is computed for each cached file, and the values are concatenated to recalculate a MD5 and output to a line of comments, so that as long as one of the cached files has changed, it will affect this line of comments, so that the entire manifest file changes, so that you do not need to manually modify the manifest file after updating the program. As you can see, if you need to cache a lot of files, this method will be very convenient, and after updating the program manifest file will be automatically modified. Of course, this is just one of the ways to use scripting manifest, and developers should make the appropriate script, depending on the situation.
Seven. About properties, methods, and events for offline network applications
In the manual update cache, Kayo mentions an object Window.applicationcache that contains properties, methods, and events related to offline network applications, in addition to the Status property and the update () method involved above. There are other relevant content, which are described in more detail below.
1. Properties
The Window.applicationcache object has an attribute status that displays different values and status numbers based on the current cache state, with the following property values:
- uncached The cache status is not started. Status code: 0
- Idle empty state. Status Code: 1
- CHECKING is checking to see if the manifest file exists. Status Code: 2
- downloading is downloading the cache file. Status Code: 3
- updateready update download completed, waiting for update status. Status Code: 4
- OBSOLETE obsolete state. Status Code: 5
2. Methods
Next, is the relevant method, as follows:
- Update () detects if the manifest file associated with the document has been modified and updates the cache if there are any modifications. If the manifest file does not exist or the cache is deprecated, a invalidstateerror error is thrown.
- The abort () user Agent sends a signal to the current cache object, aborts the download of the application cache, and if the page does not use an offline network application, the method will no longer perform any action after the signal is tried.
- SwapCache () performs a local cache update manually and can only be called in the event callback function when the Updataready event is triggered. However, it is important to note that the method does not immediately update the cache file and still needs to refresh the page for it to take effect. If the document associated with the manifest document does not exist, a invalidstateerror error is thrown.
3. Events
In addition to properties and methods, the Window.applicationcache object will trigger events on its body based on some circumstances, and developers should be aware of these events and, depending on the event being triggered, can understand the work of an offline cache that is working, and then make the appropriate processing according to different situations.
- checking Browser detects the presence of an manifest attribute on an HTML tag, it checks to see if the associated manifest file exists and triggers the checking event.
- The noupdate is triggered when it detects that the manifest is not updated (that is, not modified).
- Triggered when the downloading cache is downloaded.
- Progress Download Progress (staged event).
- cached has downloaded the appropriate resources according to the requirements specified in the manifest file.
- When Updateready is updated, the appropriate resources have been re-downloaded according to the requirements specified in the manifest file.
- obsolete manifest file request occurs when a 404 or 410 error occurs, this event indicates that the cache has been deleted.
- Error The Error event will be triggered in the following four scenarios: 1. Manifest file request occurs with a 404 or 410 error; 2. The manifest file has not been modified, but the page does not correctly reference manifest; 3. A fatal error occurred while updating resources based on the manifest file (such as the Invalidstateerror error mentioned above); 4. The manifest file is modified when the resource is being updated.
Here Kayo need to point out that these events are not all triggered in a cache process, such as error (the first three cases), Updateready, Obsolete, noupdate, cached are a cache process of the final event, in a single cache process will only One of them appears. Again, such as cached event, must have download resources and triggered after completion, that is, the second time to open the page and manifest no modification is not triggered cached event (no download resources), developers should carefully pay attention to each event's trigger time, to determine the different circumstances should use what kind of event.
This example, using AddEventListener to monitor the cached event, detects a popup prompt when the cached event occurs, which means that the offline resource has been downloaded.
1234567 |
if (Window.applicationcache) { window.applicationcache.addeventlistener ( ' cached ' function () { alert ( ' cached ' &NBSP;&NBSP;&NBSP;&NBSP; true } |
Eight. Full instance Demo
In order to give readers a better understanding of the use of offline Web applications, the above-mentioned example is described as a full demo (in order to simplify the example structure, only use AddEventListener listener event, please use Chrome, Firefox and other modern browsers to browse the demo )。
Full Demo.
This article was published by Kayo Lee, this article link: http://kayosite.com/web-app-by-jquery-mobile-and-html5-offline-web-applications.html
Develop WEB APP--HTML5 offline caching using JQuery Mobile and HTML5