Guo Zongbao, software engineer, IBM
Introduction:Web encourages personal participation. Everyone is the author of web content. If the web application can provide offline functions and allow users to write content in areas without a network (such as aircraft) or when the network is broken, wait until there is a network, and then synchronize to the Web, which greatly facilitates the user's use. HTML5, as a new generation of HTML standards, includes support for offline functions. This article describes the offline HTML5 functions, such as offline resource caching, online status detection, and local data storage. It also illustrates how to use the new HTML5 features to develop offline applications.
Introduction to HTML5 offline Functions
HTML5 is a new generation of HTML standards currently under discussion. It represents the latest development direction in the current web field. In the HTML5 standard, new and diverse content description tags are added to directly support functions such as form verification, video and audio tags, drag and drop of webpage elements, offline storage, and working threads. One of the new features is the support for Offline Application Development.
Develop a web application that supports offlineProgramDevelopers usually need to use the following three features:
- Offline resource cache: You need to specify the resource files required when the application is offline. In this way, the browser can cache these files locally when they are online. After that, when the user accesses the application program offline, these resource files are automatically loaded, so that the user can use them normally. In HTML5, the cache manifest file is used to specify the resources to be cached, and automatic and manual cache update methods are supported.
- Online status detection: developers need to know whether the browser is online so that they can handle the online or offline status. In HTML5, two methods are provided to check whether the current network is online.
- Local Data Storage: When offline, you must be able to store data locally to synchronize data online to the server. To meet different storage requirements, HTML5 provides two storage mechanisms: Dom storage and web SQL database. The former provides easy-to-use key/value pairs, while the latter provides basic relational database storage functions.
Although HTML5 is still in the draft State, many functions have been implemented by mainstream browsers. The latest versions of chrome, Firefox, Safari, and opera all provide complete support for HTML5 offline functions. IE8 also supports online status detection and Dom storage. The following describes the offline HTML5 functions, including offline resource caching, online status detection, Dom storage, and Web SQL database. Finally, a simple web program is used to describe how to develop offline applications using HTML5.
Back to Top
Offline resource Cache
To allow users to continue accessing Web applications offline, developers need to provide a cache manifest file. This file lists all resources that need to be used offline. the browser will cache these resources locally. This section uses an example to demonstrate the purpose of the cache manifest file, describe its writing method in detail, and finally describe the cache update method.
Cache manifest example
We use the example provided by W3C. Clock web applications are composed of three files named clock.html?"“clock.css "and" clock. js.
Listing 1. Clock applicationsCode
<! -- Clock.html --> <! Doctype HTML> |
When the user crashes clock.html in the off-line status, the page cannot be displayed. To support offline access, developers must add the cache manifest file to specify the resources to be cached. In this example, the cache manifest file is "clock. manifest", which declares three slow resource files named clock.html##clock.css "and" clock. js ".
Listing 2. Clock. manifest code
Cache manifest clock.html clock.css clock. js |
After the cache manifest file is added, modify “clock.html to set the manifest attribute of the <HTML> tag to "clock. manifest ". The modified export clock.html code is as follows.
Listing 3. clock.html code after setting manifest
<! -- Clock.html --> <! Doctype HTML> <HTML manifest = "clock. manifest "> |
After modification, when the user is online, the browser will slowly store the clock.html#“clock.css and "clock. js" files. When the user is offline, the Web application can also be used normally.
Cache manifest format
The format to be followed when writing the cache manifest file in the following manual.
- The first line must be cache manifest.
- Then, each row lists a resource file name to be cached.
- Lists the whitelists for online access as needed. All resources in the whitelist will not be cached and will be accessed online. Declares that the whitelist uses a network: identifier.
- If you want to add resources to be cached after the whitelist, you can use cache: identifier.
- To declare the slave URI when a URI cannot be accessed, you can use fallback: identifier. Each row after the URI contains two Uris. When the first URI is inaccessible, the browser tries to use the second Uri.
- The comment must start.
The code in Listing 4 provides examples of using various identifiers in cache manifest.
Listing 4. cache manifest sample code
Cache manifest # The last line must be written. Images/sound-icon.png images/background.png Network: comm. cgi |
# The following are other resources to be cached. In this example, there is only one CSS file.
Cache: style/default.css fallback:/files/projects/Projects |
Update Cache
Applications can wait for the browser to automatically update the cache, or manually trigger the update using the Javascript interface.
- Automatic update
In addition to caching resources when you first access a web application, the browser updates the cache only when the cache manifest file changes. The resource file in the cache manifest does not trigger the update.
- Manual Update
You can also use the window. applicationcache interface to update the cache. The method is to check the value of window. applicationcache. Status. If it is updateready, you can call window. applicationcache. Update () to update the cache. The sample code is as follows.
Listing 5 manually updating the cache
If (window. applicationcache. Status = Window. applicationcache. updateready) {window. applicationcache. Update ();} |
Back to Top
Online status detection
If the web application is only a combination of some static pages, you can use the cache manifest to cache resource files and then support offline access. However, with the development of the Internet, especially the popular concept of Web2.0, the data submitted by users has gradually become the mainstream of the Internet. When developing a web application that supports offline processing, you must consider how to allow users to operate data offline. Offline data is stored locally. After being online, data is synchronized to the server. To achieve this, developers must first know whether the browser is online. HTML5 provides two ways to check whether the event is online: navigator. Online and online/offline events.
- Navigator. Online
The navigator. Online attribute indicates whether the current status is online. True indicates online. False indicates offline. When the network status changes, the value of navigator. Online also changes. Developers can obtain the network status by reading its value.
- Online/offline events
When developing offline applications, it is usually not enough to obtain the network status through navigator. Online. Developers also need to be notified immediately when the network status changes, so HTML5 also provides online/offline events. When the online/offline status is switched, the online/Offline Event is triggered on the Body element and bubbles along the order of document. Body, document, and window. Therefore, developers can learn the network status by listening to their online/offline events.
Back to Top
Dom Storage
When developing a web application that supports offline functions, developers need to store data locally. Although the cookies supported by the browser can also be used to store data, the cookie length is very small (usually several K) and has limited functions. Therefore, the DOM storage mechanism is introduced in HTML5 to store key/value pairs. It is designed to provide large-scale, secure, and easy-to-use storage functions.
Dom Storage Classification
There are two types of Dom storage: sessionstorage and localstorage. Except for the following differences, the functions of these two types of storage objects are completely consistent.
- Sessionstorage is used to store data associated with the current browser window. When the window is closed, the data stored in sessionstorage will not be available.
- Localstorage is used for long-term data storage. When the window is closed, data in localstorage is still accessible. All browser windows can share localstorage data.
Dom storage Interface
Each storage object can store a series of key/value pairs. The storage interface is defined:
Interface storage {readonly attribute unsigned long length; getter domstring key (in unsigned long index); getter any getitem (in domstring key); setter creator void setitem (in domstring key, in any data); deleter void removeitem (in domstring key); void clear ();}; |
The most common interfaces are getitem and setitem. Getitem is used to obtain the value of the specified key, while setitem is used to set the value of the specified key.
Dom storage example
Here is an example of using sessionstorage. The localstorage usage is the same as that of sessionstorage. First, use setitem to add an item named "username". Its value is "developerworks ". Then, call getitem to get the value of "username" and a prompt box is displayed. Finally, call removeitem to delete "username ".
Listing 6 Dom storage sample code
<! Doctype HTML> <body> <SCRIPT> // define the 'username' variable sessionstorage in sessionstorage. setitem ('username', 'developerworks '); // access the 'username' variable alert ("your user is:" + sessionstorage. getitem ('username'); // Delete 'username' sessionstorage. removeitem ('username'); </SCRIPT> </body> |
Back to Top
Web SQL database
In addition to Dom storage, HTML5 also provides another data storage method, Web SQL database. It provides basic relational database functions and supports complex and Interactive Data Storage on pages. It can be used to store user-generated data or as a local high-speed cache for obtaining data from the server. For example, you can store email, calendar, and other data in the database. Web SQL database supports the concept of database transactions, so that even if multiple browser windows operate the same data, there will be no conflict.
Basic usage of Web SQL database
- Create and open a database
The first step to use the database is to create and open the database. The API is opendatabase. When the database already exists, opendatabase only opens the database. If the database does not exist, create an empty database and open it. Opendatabase is defined:
Database opendatabase (in domstring name, in domstring version, in domstring displayname, in unsigned long estimatedsize, in optional databasecallback creationcallback ); |
Name: Database Name.
Version: the database version.
Displayname: Display name.
Estimatedsize: Estimated database length (in bytes ).
Creationcallback: callback function.
- execute transaction processing
after opening the database, you can use the transaction API transaction. Each transaction, as an atomic operation to operate the database, will not be interrupted, thus avoiding data conflicts. Transaction is defined as:
void transaction (in sqltransactioncallback callback, in optional sqltransactionerrorcallback errorcallback, in optional sqlvoidcallback successcallback); |
callback: the transaction callback function, which can execute SQL statements.
errorcallback: Error callback function.
successcallback: callback function for successful execution.
- Execute SQL statements
In the transaction callback function callback, You can execute SQL statements. The API is executesql. Executesql is defined as follows:
Void executesql (in domstring sqlstatement, in optional objectarray arguments, in optional sqlstatementcallback callback, in optional sqlstatementerrorcallback errorcallback ); |
Sqlstatement: SQL statement.
Arguments: parameters required by SQL statements.
Callback: callback function.
Errorcallback: Error callback function.
Web SQL database example
The following example shows the basic usage of Web SQL database. It first calls opendatabase to create a database named "foodb. Then, use transaction to execute two SQL statements. The first SQL statement creates a table named "foo", and the second SQL statement inserts a record into the table.
Listing 7 sample code of Web SQL database
VaR DB = opendatabase ('foodb', '1. 0', 'foodb', 2*1024); dB. transaction (function (TX) {tx.exe cutesql ('create table if not exists Foo (ID unique, text) '); tx.exe cutesql ('insert into Foo (ID, text) values (1, "foobar ")');}); |
Back to Top
Offline Application Example
Finally, an example is provided to illustrate the basic method for developing offline applications using HTML5. This example uses the offline resource caching, online status detection, Dom storage, and other functions mentioned above. Suppose we develop a web application for convenience management, where users can add and delete the notes. It supports the offline function, allows users to add or delete NOTES offline, and can be synchronized to the server after being online.
- application page
the program interface is very simple, as shown in 1. You can click the "new note" button to create a new note in the pop-up box. Double-click a note to delete it.
figure 1. application page
the source file of this page is index.html, and its code is shown in listing 8.
List 8 page HTML code
declare a button and an unordered list in the body. When you press the "new note" button, the newnote function is called to Add a new Note. The unordered list is initially empty, which is used to display the convenience list.
- Cache manifest File
Define the cache manifest file and declare the resources to be cached. In this example, four files, including index.html, server. JS, Data. JS, and UI. JS, are saved. In addition to the preceding built-in index.html, "server. js", "data. js", and "UI. js" contain server-related, data storage, and user interface code. The cache manifest file is defined as follows.
Listing 9 cache manifest File
Cache manifest index.html server. js data. js UI. js |
- User Interface code
The user interface code is defined in Ui. js.
Listing 10 UI code UI. js
Function newnote () {var Title = Window. prompt ("new note:"); If (title) {Add (title) ;}} function add (title) {// Add adduiitem (title) on the page ); // Add adddataitem (title) to the data;} function remove (title) {// Delete removeuiitem (title) from the interface ); // Delete removedataitem (title) from the data;} function adduiitem (title) {var item = document. createelement ("Li"); item. setattribute ("ondblclick", "remove ('" + title + "')"); item. innerhtml = title; var list = document. getelementbyid ("list"); list. appendchild (item);} function removeuiitem (title) {var list = document. getelementbyid ("list"); For (VAR I = 0; I <list. children. length; I ++) {If (list. children [I]. innerhtml = title) {list. removechild (list. children [I]) ;}} |
The code in Ui. js contains interface operations for adding and deleting tabs.
- Click "new note". The newnote function is called.
- The newnote function dialog box is displayed. You can enter the new tab content. Newnote calls the Add function.
- The add function calls adduiitem and adddataitem to add page elements and data respectively. The adddataitem code will be listed later.
- The adduiitem function adds an item to the page list. It also indicates that the ondblclick event processing function is remove, so that the double-click operation can delete the notes.
- When you double-click a tab, the remove function is called.
- The remove function calls removeuiitem and removedataitem respectively to delete page elements and data. Removedataitem will be listed later.
- The removeuiitem function deletes the corresponding items in the page list.
- Data storage code
The data storage code is defined in data. js.
Listing 11 data storage code data. js
VaR storage = Window ['localstore']; function adddataitem (title) {If (navigator. online) // online status {addserveritem (title);} else // offline status {var STR = storage. getitem ("toadd"); If (STR = NULL) {STR = title;} else {STR = STR + "," + title;} storage. setitem ("toadd", STR) ;}} function removedataitem (title) {If (navigator. online) // online status {removeserveritem (title);} else // offline status {var STR = Storage. Getitem ("toremove"); If (STR = NULL) {STR = title;} else {STR = STR + "," + title;} storage. setitem ("toremove", STR) ;}} function syncwithserver () {// if the current status is offline, no processing is required if (navigator. online = false) return; var I = 0; // Add the operation var STR = storage synchronously with the server. getitem ("toadd"); If (STR! = NULL) {var additems = Str. split (","); for (I = 0; I <additems. length; I ++) {adddataitem (additems [I]);} storage. removeitem ("toadd");} // synchronize the delete operation with the server STR = storage. getitem ("toremove"); If (STR! = NULL) {var removeitems = Str. split (","); for (I = 0; I <removeitems. length; I ++) {removedataitem (removeitems [I]);} storage. removeitem ("toremove");} // delete all tabs in the interface var list = document. getelementbyid ("list"); While (list. lastchild! = List. firstelementchild) list. removechild (list. lastchild); If (list. firstelementchild) list. removechild (list. firstelementchild); // obtain all the tabs from the server and display var allitems = getserveritems (); If (allitems! = "") {Var items = allitems. split (","); for (I = 0; I <items. length; I ++) {adduiitem (items [I]) ;}} |
Window. addeventlistener ("online", syncwithserver, false );
The code in data. js includes adding notes, deleting notes, and synchronizing data with the server. The new HTML5 functions such as navigator. Online attributes, online events, and Dom storage are used.
- Use navigator. Online to determine whether the service is online.
- If it is online, call addserveritem to directly store the data on the server. Addserveritem will be listed later.
- If it is offline, add the data to the "toadd" item of localstorage.
- Delete Note: removedataitem
- Use navigator. Online to determine whether the service is online.
- If it is online, call removeserveritem to directly delete data from the server. Removeserveritem will be listed later.
- If it is offline, add the data to the toremove item of localstorage.
- Data Synchronization: syncwithserver
In the last row of data. JS, register the window online event processing function syncwithserver. When an online event occurs, syncwithserver is called. Its functions are as follows.
- If navigator. Online indicates that it is offline, no operation is performed.
- Add all data of the "toadd" item in localstorage to the server and delete the "toadd" item.
- Delete all data of the "toremove" item in localstorage from the server and delete the "toremove" item.
- Delete all tabs in the current page list.
- Call getserveritems to obtain all tabs from the server and add them to the page list. Getserveritems will be listed later.
-
- Server code
Server-related code is defined in server. js.
List 12 server-related code server. js
Function addserveritem (title) {// Add one to the server} function removeserveritem (title) {// delete one from the server} function getserveritems () {// return to the tag list stored on the server} |
As this part of the code is related to the server, only the functions of each function are described here. The specific implementation can be compiled based on different servers.
- Add one to the server: addserveritem
- Delete an item in the server: removeserveritem
- Return to the list of tabs stored on the server: getserveritems
Back to Top
Summary
This article introduces HTML5 to support the new powerful functions of offline applications. By reading this article, you will be able to learn the basic usage of the offline-related features in HTML5, and learn how to develop offline Web applications using HTML5.
References
- W3C HTML5 specification: a comprehensive description of the HTML5 specification.
- Whatwg homepage: whatwg is the creator of HTML5 standards.
- Mozilla Offline Application: the examples in this Article refer to its implementation.
- Safari Offline Application Development Guide: used safari to develop offline applications.
- Developerworks Web Development Area: through a dedicated web technologyArticleAnd tutorials to expand your skills in website development.
- Developerworks Ajax Resource Center: this is an all-in-one center for Ajax programming model information, including many documents, tutorials, forums, blogs, Wiki and news. Any new Ajax information can be found here.
- Developerworks Web 2.0 Resource Center, an all-in-one center for Web 2.0-related information, including a large number of Web 2.0 technical articles, tutorials, downloads, and related technical resources. You can quickly learn about the concepts of Web 2.0 through the Web 2.0 getting started Section.
About the author
Guo Zongbao is now working in the Lotus Development Center of IBM China Software Development Lab and is currently engaged in Customer Support for Lotus quickr. Have a strong interest in Web Services and Web 2.0 related technologies. You can go to my developerworksCommunityHttp://www.ibm.com/?works/my=works/profiles/user/nkhit.