HTML5 Developing offline applications

Source: Internet
Author: User
Tags sessionstorage

HTML5 Offline Feature Introduction

HTML5 is a new generation of HTML standards currently being discussed, representing the latest developments in the Web world. In the HTML5 standard, a new variety of content description tags are added, which directly supports such functions as form verification, video audio tags, drag-and-drop of webpage elements, offline storage, and work threads. One of the new features is support for offline application development.

When developing a WEB application that supports offline, developers typically need to use the following three areas of functionality:

    1. Offline resource caching: A way to indicate which resource files are required for an application to work offline. This allows the browser to cache the files locally when they are online. Thereafter, when the user accesses the application offline, the resource files are loaded automatically, allowing the user to work properly. HTML5, the cache manifest file indicates which resources need to be cached and supports both automatic and manual cache update methods.
    • Online Status detection: Developers need to know if the browser is online, so that they can deal with the status of online or offline. In HTML5, two ways to detect whether the current network is online is provided.
    • Local data storage: When offline, you need to be able to store data locally so that you can sync to the server when you are online. To meet different storage requirements, HTML5 provides the DOM Storage and Web SQL Database two storage mechanisms. The former provides easy-to-use key/value for storage, while the latter provides basic relational database storage capabilities.

Although HTML5 is still in the draft state, many of the major browsers have implemented a number of these features. The latest versions of Chrome, Firefox, Safari and Opera all provide full support for HTML5 offline functionality. IE8 also supports the online presence detection and DOM Storage functionality. The offline resource cache, online status detection, DOM Storage, and Web SQL Database in the HTML5 offline feature are described below, and finally a simple Web program is used to illustrate how to develop offline applications using HTML5.

Offline Resource Caching

To enable users to continue accessing the Web app while offline, developers need to provide a cache manifest file. This file lists all the resources that need to be used offline, and the browser caches the resources locally. This section first shows the purpose of the cache manifest file by an example, then describes its writing method in detail, and finally explains how the cache is updated.

Cache Manifest Example

We use the examples provided by the show to illustrate. The Clock Web app consists of three files "clock.html", "Clock.css" and "Clock.js".

Listing 1. Clock App Code
(!--clock.html-) (! DOCTYPE HTML (HTML) (head) (title) Clock (/title) (script src= "Clock.js") (/script) (link rel= "stylesheet" href= "  Clock.css ") (/head) (body) (p) The time is: (Output id=" clock ") (/output) (/P) (/body) (/html) output {font:2em sans-serif; } setTimeout (function () {document.getelementbyidx_xx_x (' clock '). Value = new Date ();}, 1000);

When a user accesses "clock.html" while offline, the page cannot be displayed. To support offline access, developers must add the cache manifest file to indicate which resources need to be cached. The cache manifest file in this example is "Clock.manifest", which declares 3 resource files "clock.html", "Clock.css", and "clock.js" that need to be cached.

Listing 2. Clock.manifest Code
CACHE MANIFEST clock.html clock.css clock.js

After adding the cache manifest file, you also need to modify "clock.html" to set the manifest property of the label to "Clock.manifest". The modified "clock.html" code is as follows.

Listing 3. Set the clock.html code after manifest
(!--clock.html-) (! DOCTYPE html) (HTML manifest= "Clock.manifest") (head) (title) clock (/title) (script src= "Clock.js") (/script) (Link rel= " Stylesheet "href=" Clock.css ") (/head) (body) (p) The time is: (Output id=" clock ") (/output) (/P) (/body) (/html)

Once modified, the browser caches "clock.html", "Clock.css", and "clock.js" files when the user accesses "clock.html" online, and the Web app can be used when the user is offline.

Cache manifest Format

The following is a description of the format to be followed for writing the cache manifest file.

    1. The first line must be the CACHE MANIFEST.
    • Thereafter, each row is given a resource file name that needs to be cached.
    • Whitelist of online access can be listed as needed. All resources in the whitelist are not cached and will be accessed directly online when used. Declares a whitelist using the NETWORK: identifier.
    • If you want to add resources that need to be cached after the whitelist, you can use the cache: identifier.
    • If you want to declare a substitute URI when a URI cannot be accessed, you can use the FALLBACK: identifier. Each subsequent line contains two URIs, and when the first URI is inaccessible, the browser attempts to use the second URI.
    • Note to start with the # number for a different line.

The code in Listing 4 gives examples of the use of various identifiers in cache manifest.

Listing 4. Cache Manifest Sample Code
The previous line of the CACHE MANIFEST # must be written. Images/sound-icon.png Images/background.png NETWORK:comm.cgi

# Here are some other resources that need to be cached, in this case there is only one CSS file.

Cache:style/default.css FALLBACK:/files/projects/projects
Update cache

The application can wait for the browser to automatically update the cache, or it can trigger the update manually using the Javascript interface.

    1. Automatic Updates

      In addition to caching resources for the first time a web app is accessed, the browser only updates the cache when the cache manifest file itself changes. A change in the resource file in the cache manifest does not trigger the update.

    • Manual update

      Developers can also use the Window.applicationcache interface to update the cache. The method is to detect the value of window.applicationCache.status, and if it is updateready, you can call Window.applicationCache.update () to update the cache. The demo code is as follows.

Listing 5 manually updating the cache
if (Window.applicationCache.status = = Window.applicationCache.UPDATEREADY) {window.applicationCache.update (); }

Back to top of page

On-line status detection

If the WEB application is just a combination of some static pages, then the cache manifest caches the resource files and then allows offline access. However, with the development of Internet, especially the Web2.0 concept, the data submitted by users has become the mainstream of the internet gradually. So when developing a WEB application that supports offline, you can't just be content with static pages, but also how to get users to manipulate data while offline. When offline, the data is stored locally, and the data is synchronized to the server after online. To do this, the developer must first know whether the browser is online or not. HTML5 provides two ways to detect whether online: Navigator.online and Online/offline events.

    1. Navigator.online

      The Navigator.online property indicates whether it is currently online. If true, indicates online, or if False, is offline. When the network state changes, the value of the navigator.online changes as well. The developer can get the network status by reading its value.

    • Online/offline Events

      When developing offline applications, it is often not enough to get the network state via 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 switch occurs, the Online/offline event is triggered on the body element and bubbled along the order of Document.body, document, and window. As a result, developers can learn about network status by listening to their online/offline events.

Back to top of page

DOM Storage

When developing WEB applications that support offline functionality, developers need to store data locally. Cookies supported by the current browser can also be used to store data, but the cookie is very small in length (usually several k) and has limited functionality. As a result, the DOM Storage mechanism is introduced in HTML5 to store key/value pairs, which are designed to provide large-scale, secure, and easy-to-use storage capabilities.

DOM Storage Classification

DOM Storage is divided into two categories: Sessionstorage and Localstorage. In addition to the following differences, the functions of these two types of storage objects are fully consistent.

    1. The sessionstorage is used to store data associated with the current browser window. When the window is closed, the data stored in the Sessionstorage will not be available.
    • Localstorage for long-term storage of data. When the window is closed, the data in the Localstorage can still be accessed. All browser windows can share Localstorage data.
DOM Storage Interface

Each Storage object can store a series of key/value pairs, and the Storage interface is defined as:

Interface Storage {readonly attribute unsigned long length; Getter domstring key (in unsigned long index); getter any Geti TEM (in Domstring key); Setter creator void SetItem (in Domstring key, in any data); deleter void RemoveItem (in domstring key); void Clear (); };

The most commonly used interfaces are GetItem and SetItem. The GetItem is used to get the value of the specified key, and SetItem is used to set the value of the specified key.

DOM Storage Example

Here is an example of using Sessionstorage, with the same use of localstorage. First, an item named "UserName" was added with SetItem and its value is "Developerworks". Then, call GetItem to get the value "UserName", and a pop-up prompt box displays it. Finally, call RemoveItem to delete "UserName".

Listing 6 DOM Storage sample code
(! DOCTYPE HTML (HTML) (body) (script)//define ' userName ' variable Sessionstorage.setitem in sessionstorage (' UserName ', ' Developerworks '); Access ' userName ' variable alert ("Your user is:" + sessionstorage.getitem (' userName ')); Finally delete ' UserName ' Sessionstorage.removeitem (' userName '); (/script) (/body)
(/html)
Web SQL Database
In addition to DOM Storage, there is another way to store data in HTML5 Web SQL database. It provides basic relational database functionality to support complex, interactive data storage on the page. It can be used either to store user-generated data or as a local cache to fetch data from the server. For example, you can store e-mails, schedules, and other data in a database. The Web SQL database supports the concept of databases transactions, which ensures that even multiple browser windows operate on the same data without conflicting results.
Web SQL Database Basic usage
    1. Create and open a database

The first step in using a database is to create and open the database, and the API is OpenDatabase. When the database already exists, OpenDatabase simply opens the database, and if the database does not exist, create an empty database and open it. The definition of OpenDatabase is:
Database OpenDatabase (in Domstring name, in domstring version, in Domstring DisplayName, in unsigned long estimatedsize, I N optional databasecallback creationcallback);

Name: Database name.
Version: Database versions.
DisplayName: Display name.
EstimatedSize: The estimated length of the database, in bytes.
Creationcallback: callback function.
    1. Perform transaction processing

      After you open the database, you can use the transaction API transaction. Each transaction acts as an atomic operation of the database and is not interrupted, thereby avoiding data collisions. The definition of transaction is:

void transaction (in Sqltransactioncallback callback, in optional Sqltransactionerrorcallback errorcallback, in optional Sqlvoidcallback successcallback);

Callback: A transaction callback function in which SQL statements can be executed.
Errorcallback: Error callback function.
Successcallback: Executes the successful callback function.
    • Execute SQL statement

      In the callback function callback of the transaction, the SQL statement can be executed, and the API is ExecuteSQL. The definition of ExecuteSQL is:

void ExecuteSQL (in domstring sqlstatement, in optional objectarray arguments, in optional sqlstatementcallback callback, I N optional sqlstatementerrorcallback errorcallback);

The Sqlstatement:sql statement.
The arguments required by the ARGUMENTS:SQL statement.
Callback: Callback function.
Errorcallback: Error callback function.
Web SQL Database Sample

The basic usage of Web SQL Database is illustrated below with an example. It first calls OpenDatabase to create a database named "Foodb". Then execute two SQL statements using transaction. The first SQL statement creates a table named "Foo", and the second SQL statement inserts a record into the table.
Listing 7 Web SQL Database Sample Code
var db = OpenDatabase (' Foodb ', ' 1.0 ', ' Foodb ', 2 * 1024); Db.transaction (Function (TX) {tx.executesql (' CREATE TABLE IF not EXISTS foo (id unique, text) '); Tx.executesql (' INSERT in to Foo (ID, text) VALUES (1, "foobar"); });

Back to top of page
Offline Application Examples

Finally, an example is used to illustrate the basic method of developing offline applications using HTML5. This example uses the previously mentioned features such as offline resource caching, online status detection, and DOM Storage. Suppose we develop a sticky note-managed WEB application where users can add and remove notes. It supports offline functionality, allows users to add and remove notes offline, and can be synced to the server later on-line.
    1. Application Page

      The interface of this program is very simple, as shown in 1. The user clicks the "New Note" button to create a new note in the pop-up box, and double-click on a note to delete it.

Figure 1. Application Page

The source file for this page is index.html, and its code is shown in Listing 8.
Listing 8 Page HTML code
(HTML manifest= "Notes.manifest") (head) (script type= "Text/javascript" src= "Server.js") (/script) (Script type= "text/ JavaScript "src=" Data.js ") (/script) (script type=" Text/javascript "src=" Ui.js ") (/script) (title) Note List (/title) (/ Head) (Body onload = "syncwithserver ()") (Input type= "button" value= "New Note" onclick= "Newnote ()") (UL id= "list") (/UL) (/ Body) (/html)

A button and an unordered list are declared in the body. When the "New note" button is pressed, the Newnote function is called, which is used to add a new note. The unordered table is initially empty, and it is the list used to display the notes.
    • Cache manifest File

      Define the cache manifest file, declaring the resources that need to be cached. In this example, 4 files such as "index.html", "Server.js", "Data.js" and "ui.js" need to be cached. In addition to the "Index.html" listed earlier, "Server.js", "Data.js", and "Ui.js" contain server-related, data-store, and user-interface code, respectively. 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 user Interface code Ui.js
function Newnote () {var title = Window.prompt ("New Note:"); if (title) {Add (title);}} function Add (title) {//Add Adduiitem (title) to the interface,//Add Adddataitem (title) to the data,} function remove (title) {//Remove from interface Remov Euiitem (title); Remove Removedataitem (title) from the data; } function Adduiitem (title) {var item = document.createelement_x_x ("li"); Item.setattribute ("OnDblClick", "Remove ('" + Title+ "')"); Item.innerhtml=title; var list = document.getelementbyidx_xx_x ("list"); List.appendchild (item); } function Removeuiitem (title) {var list = document.getelementbyidx_xx_x ("list"); for (var i = 0; i < List.children.le Ngth; i++) {if (list.children[i].innerhtml = = title) {list.removechild (list.children[i]);}}}

The code in Ui.js contains interface actions for adding notes and deleting notes.
    • Add a note
    1. The Newnote function is called when the user taps the "New Note" button.
    • The Newnote function pops up the dialog box and the user enters the new note content. Newnote calls the Add function.
    • The Add function calls Adduiitem and Adddataitem, respectively, to add page elements and data. The Adddataitem code will be listed later.
    • The Adduiitem function adds an item to the list of pages. and indicates that the handler function for the OnDblClick event is remove, which allows the double-click to delete the note.
    • Delete a note
    1. When the user double-clicks a note, the Remove function is called.
    • The Remove function calls Removeuiitem and Removedataitem, respectively, to delete page elements and data. The Removedataitem will be listed later.
    • The Removeuiitem function deletes the corresponding item in the page list.
    • Data storage Code

      The data store code is defined in Data.js.

Listing 11 data storage code Data.js
var storage = window[' Localstorage ']; function Adddataitem (title) {if (navigator.online)//Online status {addserveritem (title);} else/offline status {var str = Storage.get Item ("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 = s Torage.getitem ("Toremove"); if (str = = null) {str = title;} else {str = str + "," + title;} storage.setitem ("Toremove", str); }} function Syncwithserver () {//If the current is offline, do not need to do any processing if (Navigator.online = = false) return; var i = 0;//and Server Sync add operation var s TR = Storage.getitem ("Toadd"); if (str = null) {var additems = Str.split (","); for (i = 0; i

Window.addeventlistener ("online", Syncwithserver,false);
The code in Data.js contains data operations such as adding notes, deleting notes, and synchronizing with the server. It uses the Navigator.online property, OnLine event, DOM Storage and other HTML5 new functions.
    • Add Note: Adddataitem
    1. Determine whether online through Navigator.online.
    • If online, then call Addserveritem to store the data directly on the server. The Addserveritem will be listed later.
    • If offline, add the data to the Localstorage "Toadd" item.
    • Delete Note: Removedataitem
    1. Determine whether online through Navigator.online.
    • If online, then call Removeserveritem to delete the data directly on the server. The Removeserveritem will be listed later.
    • If offline, add the data to the Localstorage "Toremove" item.
    • Data synchronization: Syncwithserver

In the last line of Data.js, the online event handler function Syncwithserver for window is registered. Syncwithserver will be called when the online event occurs. Its functions are as follows.
    1. If navigator.online indicates that it is currently offline, no action is taken.
    • Add all the data for the "Toadd" item in Localstorage to the server and delete the "Toadd" entry.
    • Remove all data from the Localstorage "Toremove" item from the server and remove the "Toremove" entry.
    • Deletes all the notes in the current page list.
    • Call Getserveritems to get all the notes from the server and add them in the page list. The Getserveritems will be listed later.
    • Server-related code

      The server-related code is defined in Server.js.

Listing 12 server-related code server.js
function Addserveritem (title) {//Add an item to the server} function Removeserveritem (title) {//delete an item in the server} function Getserveritems () {//Returns a list of notes stored in the server}

Since this part of the code is related to the server, it only describes the functions of each function, the implementation can be based on different servers to write code.
    • Add an item to the server: Addserveritem
    • Delete an item from the server: Removeserveritem
    • Returns a list of notes stored in the server: Getserveritems
Summarize

This article describes the powerful features that HTML5 has added to support offline applications. By reading this article, readers can understand the basic usage of the offline correlation features in HTML5, so as to master the method of developing Web off-line application using HTML5.

HTML5 Developing offline applications

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.