Introduce several storage methods in HTML5




In general,

before h5, the storage was mainly using cookies. The disadvantage of cookies is that they carry data in the request header, and the size is within 4k. Main Domain pollution.

Main applications: shopping cart, customer login

For IE browser, there is UserData, the size is 64k, only IE browser supports. Let 's learn HTML5 several storage methods together with

the Brothers (www.lampbrother.net ) HTML5 course: target Solve the 4k size problem Solve the problem that the request header often contains stored information Solve relational storage Cross browser 1. Local storage Localstorage storage method: stored in the form of key-value pair (Key-Value), permanently stored, and never expired unless manually deleted. Size: 5M per domain name Support: 911587-20160723133547154-1865674181 Note: IE9 localStorage does not support local files, you need to deploy the project to the server to support it! Detection method: JavaScript if(window.localStorage){ alert('This browser supports localStorage'); }else{













































alert('This browser does NOT supportlocalStorage');

}

if(window.localStorage){

alert('This browser supports localStorage');

}else{

alert('This browser does NOT supportlocalStorage');

}



Common API:

getItem / /Get record



setIten//Set record



removeItem//Remove record



key//Get the value corresponding to the key



clear//Clear record



2. Local storage sessionstorage LocalStorage

in HTML5's local storage API is the same as sessionStorage in usage , the difference is that sessionStorage is emptied after closing the page, while localStorage will always be saved.



3. Offline cache (application cache)

locally caches the files required by the application

Usage :

① Configure the manifest file On the



page :

XHTML

<!DOCTYPE HTML>

<htmlmanifest="demo.appcache">



</html>

<!DOCTYPE HTML>

<htmlmanifest="demo.appcache">

...

</html>



Manifest files:



manifest files are simple text files that tell the browser what to cache (and what not to cache) ).



The manifest file can be divided into three parts:



① CACHE MANIFEST – files listed under this heading will be cached after the first download



② NETWORK – files listed under this heading require a connection to the server and will not be cached



③ FALLBACK – here The file listed under the title specifies the fallback page (such as a 404 page) when the page is unreachable



. Complete demo:

CACHE MANIFEST

# 2016-07-24 v1.0.0

/theme.css

/main.js



NETWORK:

login.jsp



FALLBACK:

/ html/ /offline.html

CACHE MANIFEST

# 2016-07-24 v1.0.0

/theme.css

/main.js



NETWORK:

login.jsp



FALLBACK:

On the /html/ /offline.html

server: the manifest file needs to be configured with the correct MIME-type, i.e. "text/cache-manifest".



Common API:



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



0 (UNCACHED): No cache, that is, there is no application cache related to the page



1 (IDLE): Idle, that is, the application cache has not been



updated2 (CHECKING): Checking, that is, downloading the description file and checking for updates



3 (DOWNLOADING): Downloading, that is, the application cache is downloading the resources specified in the description file



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



5 ( IDLE) : Obsolete, that is, the description file of the application cache no longer exists, so the page can no longer access the application cache





. Related events:



Indicates that the state of the application cache has changed:



checking : Triggered when the browser is looking for updates for the application cache



error : Checking Triggered when an error is sent during an update or download of a resource



noupdate : Triggered when the description file is checked and found that the file has not changed downloading : Triggered when the download of the app



cached resource is started Cached is triggered when the new application cache of the page is downloaded : triggered when the application cache is fully available

















Three advantages of Application Cache:



① Offline browsing



② Improve page loading speed



③ Reduce server



pressure Notes:



1. Browsers may have different capacity limits for cached data (some browsers set a limit of 5MB per site )

2. If the manifest file, or one of the files listed inside cannot be downloaded normally, the entire update process will be regarded as a failure, and the browser will continue to use the old cache

. 4. The

browser will automatically cache the HTML file referencing the manifest file, which leads to the need to update the version if the HTML content is changed.

5. The CACHE in the manifest file has nothing to do with the position order of NETWORK and FALLBACK. If it is an implicit declaration, it needs to be at the top

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

. 7. After updating the version, it must be refreshed once. To start a new version (the page will be refreshed once), you need to add a monitoring version event.

8. Even if other pages in the site do not set the manifest attribute, the requested resources will be accessed from the cache if they are in the cache.

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



. Click me for more information!



The difference between offline cache and traditional browser cache:



1. Offline cache is for the entire application, browser cache is a single file



2. Offline cache can still open the page after the network is disconnected, browser cache is not good



3. Offline cache can actively notify the browser to update resource



4. Web SQL



relational database, accessing

the Web SQL database API through SQL statements is not part of the HTML5 specification, but it is an independent specification that introduces a set of APIs that use SQL to manipulate client databases.

Support:

WebSQL databases work in the latest versions of Safari, Chrome and Opera browsers.

Core methods:



①openDatabase: This method uses an existing database or a new database to create a database object.



②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:



JavaScript



var db = openDatabase('mydb', '1.0', 'TestDB', 2 * 1024 * 1024,fn);

//The five parameters corresponding to the openDatabase() method are: database name, version number, Description text, database size, create callback

var db = openDatabase('mydb', '1.0', 'TestDB', 2 * 1024 * 1024,fn);

//The five parameters corresponding to the openDatabase() method are: database name , version number, description text, database size, create callback

Execute query operation:



JavaScript



var db = openDatabase('mydb', '1.0', 'TestDB', 2 * 1024 * 1024);

db.transaction(function (tx) {

  tx.executeSql('CREATE TABLE IF NOT EXISTS WIN (id unique, name)');

});

var db = openDatabase('mydb', '1.0', 'TestDB', 2 * 1024 * 1024);

db.transaction(function (tx) {

   tx.executeSql('CREATE TABLE IF NOT EXISTS WIN(id unique, name)');

});

插入数据: 



JavaScript



var db = openDatabase('mydb', '1.0', 'TestDB', 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")');

});

var db = openDatabase('mydb', '1.0', 'TestDB', 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")');

});

读取数据:



JavaScript



db.transaction(function (tx) {

   tx.executeSql('SELECT * FROM WIN', [],function (tx, results) {

     var len = results.rows.length, i;

     msg = "<p>查询记录条数: " +len + "</p>";

     document.querySelector('#status').innerHTML +=  msg;

   

     for (i = 0; i < len; i++){

        alert(results.rows.item(i).name );

     }

   

   },null);

});

db.transaction(function (tx) {

  tx.executeSql(' 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);

});

It can be seen from these operations that basically use SQL statements to perform database-related operations. If you know MySQL, this should be easier to use.



5. IndexedDB



The IndexedDB API (as part of HTML5) is useful for creating data-intensive offline HTML5 web applications with rich locally stored data. It also helps cache data locally, making traditional online web applications (such as mobile web applications) faster and more responsive.

Asynchronous API: Most of the

operations in IndexedDB are not our commonly used calling methods and the mode of returning results, but the mode of request-response

.

A DB object is returned, and this object is in the result. As can be seen from the above figure, except for the result. There are also several important attributes onerror, onsuccess, onupgradeneeded (called when the version number of the database we request to open is inconsistent with the version number of the existing database). This is similar to our ajax request. After we initiate this request, we cannot be sure when it will be successful, so we need to handle some logic in the callback.



Close and delete:

JavaScript



function closeDB(db){

    db.close();

}

function deleteDB(name){

    indexedDB.deleteDatabase(name);

}

function closeDB(db){

    db.close();

}

function deleteDB(name) {

    indexedDB.deleteDatabase(name);

}

Data storage:

There is no concept of table in indexedDB, but objectStore. A database can contain multiple objectStores. ObjectStore is a flexible data structure that can store various types of data. That is to say, an objectStore is equivalent to a table, and each piece of data stored in it is associated with a key.



We can use a specified field in each record as the key value (keyPath), or we can use an automatically generated incremental number as the key value (keyGenerator), or we can not specify it. The type of selection key is different, and the data structure that the objectStore can store is also different. The above are the HTML5 storage methods

summarized . Have you learned it yet?




Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326655293&siteId=291194637