This section describes the summary of several front-end HTML5 storage methods and the front-end html5 storage methods.

Source: Internet
Author: User
Tags sessionstorage

This section describes the summary of several front-end HTML5 storage methods and the front-end html5 storage methods.

Overall situation

Before h5, cookies were used for storage. The disadvantage of cookies is that the request header carries data within 4 kb. Primary Domain pollution.

Main Applications: shopping cart and customer Logon

For IE, UserData is available, which is 64 k in size and only supported by IE.

Target

  1. Solve the Problem of 4 K size
  2. Solve the problem that request headers often contain stored information
  3. Solving relational storage problems
  4. Cross-browser

1. Local Storage

Storage Method:

It is stored as a Key-Value pair. It is permanently stored and never becomes invalid unless it is manually deleted.

Size:

5 MB per domain name

Support:

Note: IE9 localStorage does not support local files. You need to deploy the project to the server to support it!

Check Method:

if(window.localStorage){ alert('This browser supports localStorage');}else{ alert('This browser does NOT support localStorage');} 

Common APIs:

GetItem // retrieve record

SetIten // set the record

RemoveItem // remove record

Key // obtain the value corresponding to the key

Clear // clear records

Stored content:

Array, image, json, style, script... (Any content that can be serialized into strings can be stored)

2. Local Storage sessionstorage

LocalStorage and sessionStorage In the HTML5 local storage API are used in the same way. The difference is that sessionStorage is cleared after the page is closed, while localStorage is always saved.

3. Offline cache)

Locally cache the files required by the application

Usage:

① Configure the manifest File

On the page:

<!DOCTYPE HTML>

Manifest file:

A manifest file is a simple text file that informs the browser of cached content (and non-cached content ).

The manifest file can be divided into three parts:

① Cache manifest-files listed under this title will be cached after the first download

② NETWORK-the files listed under this title need to be connected to the server and will not be cached

③ FALLBACK-the files listed under this title specify the rollback page when the page cannot be accessed (such as the 404 page)

Complete demo:

CACHE MANIFEST# 2016-07-24 v1.0.0/theme.css/main.jsNETWORK:login.jsp FALLBACK:/html/ /offline.html 

On the server:The manifest file must be configured with the correct MIME-type, that is, "text/cache-manifest ".

For example, Tomcat:

<mime-mapping>     <extension>manifest</extension>     <mime-type>text/cache-manifest</mime-type></mime-mapping> 

Common APIs:

The core is the applicationCache object, which has a status attribute, indicating the current status of the application cache:

0 (UNCACHED): no cache, that is, no page-related application Cache

1 (IDLE): The application cache is not updated.

2 (CHECKING): check, that is, the description file is being downloaded and the update is checked.

3 (DOWNLOADING): The application cache is DOWNLOADING the specified resource in the description file.

4 (UPDATEREADY): The update is complete, and all resources have been downloaded.

5 (IDLE): deprecated. That is, the description file of the application cache does not exist, so the page cannot access the application cache.

Related Events:

Indicates that the application cache status changes:

Checking: triggered when the browser finds updates for the Application Cache

Error: triggered when an error is sent during Resource Check or download

Noupdate: triggered when no change is found in the description file

Downloading: triggered when the application cache resource is downloaded.

Progress: the download process is continuously triggered during the application cache process.

Updateready: triggered when the new application cache is downloaded.

Cached: triggered when the application cache is fully available

Three Advantages of Application Cache:

① Offline browsing

② Increase page loading speed

③ Reduce server pressure

Note:

1. the browser may not have the same capacity limit on the cached data (Some browsers set a limit of 5 MB for each site)

2. If the manifest file or an internal file cannot be downloaded normally, the entire update process will be deemed as failed, and the browser will continue to use the old cache.

3. the html that references manifest must be the same as the manifest file.

4. the browser automatically caches the HTML file that references the manifest file. This causes the HTML content to be updated only after the HTML content is changed.

5. the CACHE in the manifest file has no relationship with the location sequence of NETWORK and FALLBACK. If it is an implicit declaration, it must be at the beginning.

6. The resources in FALLBACK must be the same as the manifest file.

7. After the version is updated, you must refresh the page once to start the new version. You must add a version event.

8. Even if the manifest attribute is not set for other pages on the site, the requested resources are also accessed from the cache.

9. When the manifest file changes, the resource request itself also triggers an update.

Differences between offline cache and traditional browser cache:

1. The offline cache is for the entire application, and the browser cache is a single file

2. If the offline cache is disconnected, you can still open the page.

3. The offline cache can actively notify the browser to update resources.

4. Web SQL

Relational Database, accessed through SQL statements

Web SQL database API is not part of the HTML5 specification, but it is an independent specification that introduces a group of APIs that use SQL to operate the client database.

Support:

Web SQL databases can work in the latest Safari, Chrome, and Opera browsers.

Core methods:

① OpenDatabase:This method creates a database object using an existing database or a new database.

② Transaction:This method allows us to control a transaction and perform commit or rollback based on this situation.

③ ExecuteSql:This method is used to execute the actual SQL query.

Open the database:

Var db = openDatabase ('mydb', '1. 0', 'test db', 2*1024*1024, fn); // The five parameters corresponding to the openDatabase () method are: database Name, version number, description text, database size, creation callback

Perform the query operation:

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);db.transaction(function (tx) {     tx.executeSql('CREATE TABLE IF NOT EXISTS WIN (id unique, name)');}); 

Insert data:

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);db.transaction(function (tx) {   tx.executeSql('CREATE TABLE IF NOT EXISTS WIN (id unique, name)');   tx.executeSql('INSERT INTO WIN (id, name) VALUES (1, "winty")');   tx.executeSql('INSERT INTO WIN (id, name) VALUES (2, "LuckyWinty")');}); 

Read data:

Db. transaction (function (tx) {tx.exe cuteSql ('select * FROM win', [], function (tx, results) {var len = results. rows. length, I; msg = "<p> Number of query records:" + len + "</p>"; document. querySelector ('# status '). innerHTML + = msg; for (I = 0; I <len; I ++) {alert (results. rows. item (I ). name) ;}}, null );});

From these operations, we can see that SQL statements are basically used for database operations. If you use MySQL, this should be easier to use.

5. IndexedDB

The index database (IndexedDB) API (as part of HTML5) is useful for creating a data-intensive offline HTML5 Web application with rich local storage data. It also helps to cache data locally and enable traditional online Web applications (such as mobile Web applications) to run and respond faster.

Asynchronous API:

Most of the operations in IndexedDB are not commonly used call methods, but return result modes, but request-response modes, such as opening a database.

In this way, when we open the database, a DB object is actually returned, and this object is in result. It can be seen that in addition to result. There are also several important attributes: onerror, onsuccess, and onupgradeneeded (called when the version number of the database we requested to open is inconsistent with the existing database version number ). This is similar to our ajax request. After initiating this request, we cannot determine when the request is successful. Therefore, we need to process some logic in the callback.

Close and delete:

function closeDB(db){     db.close();}function deleteDB(name){     indexedDB.deleteDatabase(name);} 

Data storage:

IndexedDB does not have the table concept, but objectStore. A database can contain multiple objectstores. objectStore is a flexible data structure that can store multiple types of data. That is to say, an objectStore is equivalent to a table, where each piece of data is associated with a key.

You can use a specified field in each record as the keyPath, or use an auto-generated incremental number as the keyGenerator. The data structures that can be stored in objectStore vary depending on the type of the selected key.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.