Offline Web Storage

Source: Internet
Author: User
Tags sqlite

Caching of local cache and browser pages

The difference between a local cache and a browser Web cache

Offline caching requires a local cache of all html css, js file local cache services for the Web application throughout the Web application

Browser page caching only serves a single page,

Any Web page has a cache, and the local cache caches only the pages that you specify for caching. Web page caching is insecure and unreliable, and we don't know which pages are cached in the site and which resources are cached. The local cache is reliable, we can control the caching of those that do not have content, and developers are also able to programmatically control cached updates, exploiting more powerful offline Web applications using cached object properties and state events .

Manifest File

The local cache for Web apps is managed through the manifest file for each page

CACHE MANIFEST // required

#This is a comment

Cache// file to be cached for offline use

Index.html

Style.css

NETWORK: // files that are not stored locally cache

search.php

login.php

FALLBACK: // Two files for resources that can be accessed online when they are available, and resources that cannot be accessed online

/api offline.html

Applicationcache object: Represents the local cache, which is used to inform the local cache that it has been updated, and allows the user to manually update

When the browser updates the local cache, loading the new file triggers the updateready event of the Applicationcatche object to inform the local cache that it has been updated (it can be used to tell the user Users need to refresh manually to get the latest version of the page)

Applicationcatche.onupdateready = function () {}

The Swapcatch method is used to manually perform locally cached updates only when the Applicationcatche updateready event is triggered,updateready event occurs only if the manifest file on the server is repaired and the resource requested in the manifest file is downloaded locally

SetInterval (function () {

Manually Check for updates

Applicationcache.update ();

}, 5000);

Applicationcache.addeventlistener ("Updateready", function () {

if (Confirm (" local cache has been updated , need to refresh the screen to get the latest version of the app

Ben, is it refreshed? ")) {

(3) Updating the local cache manually

Applicationcache.swapcache ();

Reload Screen

Location.reload ();

}

}, True);

other events in Applicationcatche

function init ()

{

var Msg=document.getelementbyid ("msg");

Applicationcache.addeventlistener ("Checking", function () {

msg.innerhtml+= "checking<br/>";

}, True);

Applicationcache.addeventlistener ("Noupdate", function () {

msg.innerhtml+= "noupdate<br/>";

}, True);

Applicationcache.addeventlistener ("Downloading", function () {

msg.innerhtml+= "downloading<br/>";

}, True);

Applicationcache.addeventlistener ("Progress", function () {

msg.innerhtml+= "progress<br/>";

}, True);

Applicationcache.addeventlistener ("Updateready", function () {

msg.innerhtml+= "updateready<br/>";

}, True);

Applicationcache.addeventlistener ("Cached", function () {

msg.innerhtml+= "cached<br/>";

}, True);

Applicationcache.addeventlistener ("Error", function () {

msg.innerhtml+= "error<br/>";

}, True);

}

HTML5 has been in full swing for nearly a decade, with video, audio, images, animations, and computer interactions standardized on the HTML5 platform. More and more HTML features, support image upload drag, support localstorage, support Web SQL database, support file storage API and so on. It is a long way away and is committed to bringing the Web into a more mature application platform. Of all the cool features, what I like most is that it has the ability to cache Web apps offline.

Developing offline Web applications: three core functions

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.

2. On-line status detection: Developers need to know whether the browser is online, so that the online or offline status, to make corresponding processing. In HTML5, two ways to detect whether the current network is online is provided.

3. Local data storage: When offline, you need to be able to store the 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.

Offline storage HTML5 Web SQL Database

WEB SQL Database 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.

It also introduces a set of APIs that use SQL to manipulate client databases (Client-side database), which are asynchronous (asynchronous). The SQL language used is SQLite 3.6.19. Which SQLite is a lightweight database, occupying very low resources, support Windows/linux/unix and other mainstream operating systems, and can be combined with many programming languages, such as C#,php,java,javascript, compared to Mysql, PostgreSQL, the two open-source database management system, is processing faster. Currently iOS and Android platforms support running Web SQL Database.

var db = Window.opendatabase ("DBName", "1.0", "description", 5*1024*1024); 5MB

Db.transaction (Function (TX) {

Tx.executesql ("SELECT * from Test", [], Successcallback, errorcallback);

});

Web Workers

Main.js:

var worker = new Worker (' task.js ');

Worker.onmessage = function (event) {alert (event.data);};

Worker.postmessage (' data ');

Task.js:

Self.onmessage = function (event) {

Do some work.

Self.postmessage ("Recv ' d:" + event.data);

};

HTML5 IndexedDB: Lightweight NoSQL Database

INDEXEDDB is an important part of Html5-webstorage and is a lightweight NoSQL database.

The INDEXEDDB defines a number of interfaces for the database object, which is defined as idbdatabase.

Browser object, implemented Idbfactory only indexeddb this instance.

Five steps to create an HTML5 offline Web App

In all the cool features offered by HTML5, creating an offline cache page is one of my favorite features, and here are five steps to quickly create a HTML5 offline Web App

1. First step: Create a valid HTML5 document, HTML5 DOCTYPE is easier to remember than XHTML.

Create a file called index.html, where you can learn how to use CSS3 to plan your site layout.

Http://www.catswhocode.com/blog/create-an-adaptable-website-layout-with-css3-media-queries

2. added. htaccess Support

The cache page We are creating is called the manifest file, assuming that the server you are using is Apache, and we need to add a new directive to the. htaccess file before creating the file.

Open the. htaccess file, which is deployed in the root directory of the Web site, adding the following code:

AddType text/cache-manifest. manifest

This directive ensures that every. manifest file text cache is available. If the file does not exist, the entire cache effect will not be implemented, and the page will not be cached offline.

3. Create a. manifest file

After we created the. manifest file, things became much more interesting. Create a new file, named Offline.manifest, and embed the following code.

CACHE MANIFEST

#This is a comment

CACHE

Index.html

Style.css

Image.jpg

Image-med.jpg

Image-small.jpg

Notre-dame.jpg

Now you have a perfect list of manifest. In fact, the principle is simple, after declaring the cache, you can list the files you want to cache offline. This is more than enough for caching a simple Web page, and HTML5 's cache has some other interesting features.

CACHE MANIFEST // required

#This is a comment

Cache// file to be cached for offline use

Index.html

Style.css

NETWORK: // files that are not stored locally cache

search.php

login.php

FALLBACK: // Two files for resources that can be accessed online when they are available, and resources that cannot be accessed online

/api offline.html

In this example, the manifest file declares the cache, which is used for caching index.html and STYLE.CSS. At the same time, we declare the network to specify files that are not cached, such as the login page.

The final statement is fallback, which allows the user to be transferred to a specified page, such as in this case, if you do not plan to view the API resources offline, you can turn to the off.html page.

4. Link the manifest file to the HTML document.

After the manifest file and the main HTML document are ready, the only thing you need to do is link the manifest file to the HTML document.

The method of operation is simple, just add the manifest attribute in the HTML meta-count, the code is as follows:

Local Database

1. create an object that accesses the database //var db = OpenDatabase (' mysql ', ' 1.0 ', ' Test db ', 2*1024*1024) The database is created when the database does not exist

2. use the transaction processing // Access database call The transaction method to execute the transaction parameter as a callback function

Eg bd.transaction (Function (TX) {

tx.executesql (' CREATE TABLE IF not ' EXISTS msgdata (name text, message text, Time INTEGER) ', []);

Tx.executesql (' SELECT * from Msgdata ', [], Function (TX, RS)

{ //removealldata ();

for (var i = 0; i < rs.rows.length; i++)

{

ShowData (Rs.rows.item (i));

}

});  }); });

TX.Executesql(' sql parameter used? ', [ for? Assignment ],funsuccess,funerror)

The local cache is managed by the Mainfest file for each page .  

Browser and server interaction process:

Browser request URL,server back page, browser resolution page, server return all resources, browser processing mainfest file, server returns all files that require local cache The browser updates The local cache

Browser request mainfest-> (no update) server returns 304 ("if updated" browser again requests url-> Browser discovery cache, browser resolution cache page Browser Discovery Cache page, browser parsing cache page, browser request mainfest file--server returns updated mainfest-> browser processing mainfest-> browser returns to local cache The browser updates the local cache)

"Cached updates are not available after the local cache update, only the updated resource files can be used when you reopen this page"

by triggering the Onupdateready event of the Applicationcache object, the user is told that the local cache has been updated and that the page needs to be manually refreshed to get the latest version of the application.  

The Local Cache update operation is performed manually by triggering the Swapcache method of the Applicationcache object , and he can only use the Applicationcache object's The call is triggered in the Updataready event.  

Offline Web Storage

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.