Home > Web Front-end > H5 Tutorial > body text

Summary of several storage methods in front-end HTML5

巴扎黑
Release: 2018-05-25 11:12:28
Original
3377 people have browsed it

Overall situation

Before h5, cookies were mainly used for storage. 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 it.

Target

Solve the 4k size problem

Solve the problem that request headers often carry storage information

Solve the problem of relational storage

Cross-browser

1. Local storage localstorage

Storage method:

It is stored in the form of key-value pairs, permanently stored, and will never expire unless manually deleted.

size:

5M per domain name

Support status:

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

Detection method:

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

Commonly used API:

getItem //Get records

setIten//Set record

removeItem//Remove record

key//Get the value corresponding to key

clear//Clear the record

Stored content:

Array, picture, json, style, script. . . (Any content that can be serialized into a string can be stored)

2. Local storage sessionstorage

The usage methods of localStorage and sessionStorage in HTML5's local storage API are the same. The difference is that sessionStorage is cleared after closing the page, while localStorage will always be saved.

3. Offline cache (application cache)

Locally cache files required by the application

Usage:

①Configure manifest file

On page:

<!DOCTYPE HTML>
<html manifest="demo.appcache">
...
</html>
Copy after login

Manifest file:

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 - The files listed under this title specify the fallback page when the page cannot be accessed (such as the 404 page)

Full demo:

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

Server Above: The manifest file needs to 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>
Copy after login

Commonly used API:

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, there is no application cache related to the page

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

2 (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 completed and all resources have been downloaded

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

Related events:

Indicates changes in application cache status:

checking : Triggered when the browser is looking for updates to the app cache

error : Triggered when an error is sent during checking for updates or downloading resources

noupdate: Triggered when checking the description file and finding that the file has no changes

downloading : Triggered when downloading application cache resources

progress: Triggered by continuous downloading during the file download application cache

updateready: Triggered when the new application cache on the page is downloaded

cached: 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 internally cannot be downloaded normally, the entire update process will be regarded as a failure, and the browser will continue to use the old cache

3. The html that references the manifest must have the same origin as the manifest file and be in the same domain

4. The browser will automatically cache the HTML file that references the manifest file. This means that if the HTML content is changed, the version needs to be updated to be updated.

5. 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 front

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

7. 更新完版本后,必须刷新一次才会启动新版本(会出现重刷一次页面的情况),需要添加监听版本事件。

8. 站点中的其他页面即使没有设置manifest属性,请求的资源如果在缓存中也从缓存中访问

9. 当manifest文件发生改变时,资源请求本身也会触发更新

点我参考更多资料!

离线缓存与传统浏览器缓存区别:

1. 离线缓存是针对整个应用,浏览器缓存是单个文件

2. 离线缓存断网了还是可以打开页面,浏览器缓存不行

3. 离线缓存可以主动通知浏览器更新资源

4.Web SQL

关系数据库,通过SQL语句访问Web SQL 数据库 API 并不是 HTML5 规范的一部分,但是它是一个独立的规范,引入了一组使用 SQL 操作客户端数据库的 APIs。

支持情况:

Web SQL 数据库可以在最新版的 Safari, Chrome 和 Opera 浏览器中工作。

核心方法:

①openDatabase:这个方法使用现有的数据库或者新建的数据库创建一个数据库对象。

②transaction:这个方法让我们能够控制一个事务,以及基于这种情况执行提交或者回滚。

③executeSql:这个方法用于执行实际的 SQL 查询。

打开数据库:

var db = openDatabase(&#39;mydb&#39;, &#39;1.0&#39;, &#39;Test DB&#39;, 2 * 1024 * 1024,fn);
//openDatabase() 方法对应的五个参数分别为:数据库名称、版本号、描述文本、数据库大小、创建回调
Copy after login

执行查询操作:

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

插入数据: 

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

读取数据:

db.transaction(function (tx) {
   tx.executeSql(&#39;SELECT * FROM WIN&#39;, [], function (tx, results) {
      var len = results.rows.length, i;
      msg = "<p>查询记录条数: " + len + "</p>";
      document.querySelector(&#39;#status&#39;).innerHTML +=  msg;
    
      for (i = 0; i < len; i++){
         alert(results.rows.item(i).name );
      }
    
   }, null);
});
Copy after login

由这些操作可以看出,基本上都是用SQL语句进行数据库的相关操作,如果你会MySQL的话,这个应该比较容易用。

点我看更多教程!

5.IndexedDB

索引数据库 (IndexedDB) API(作为 HTML5 的一部分)对创建具有丰富本地存储数据的数据密集型的离线 HTML5 Web 应用程序很有用。同时它还有助于本地缓存数据,使传统在线 Web 应用程序(比如移动 Web 应用程序)能够更快地运行和响应。

异步API:

在IndexedDB大部分操作并不是我们常用的调用方法,返回结果的模式,而是请求——响应的模式,比如打开数据库的操作

这样,我们打开数据库的时候,实质上返回了一个DB对象,而这个对象就在result中。由上图可以看出,除了result之外。还有几个重要的属性就是onerror、onsuccess、onupgradeneeded(我们请求打开的数据库的版本号和已经存在的数据库版本号不一致的时候调用)。这就类似于我们的ajax请求那样。我们发起了这个请求之后并不能确定它什么时候才请求成功,所以需要在回调中处理一些逻辑。

关闭与删除:

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

数据存储:

indexedDB中没有表的概念,而是objectStore,一个数据库中可以包含多个objectStore,objectStore是一个灵活的数据结构,可以存放多种类型数据。也就是说一个objectStore相当于一张表,里面存储的每条数据和一个键相关联。

我们可以使用每条记录中的某个指定字段作为键值(keyPath),也可以使用自动生成的递增数字作为键值(keyGenerator),也可以不指定。选择键的类型不同,objectStore可以存储的数据结构也有差异。 

这个就有点复杂了。

The above is the detailed content of Summary of several storage methods in front-end HTML5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template