search
HomeWeb Front-endH5 TutorialDetailed explanation of H5 storage method

Detailed explanation of H5 storage method

Mar 26, 2018 pm 01:54 PM
html5WayDetailed explanation

This time I will bring you a detailed explanation of the H5 storage method. What are the precautions when using the H5 storage method? The following is a practical case, let’s take a look.

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 browserThere is UserData, the size is 64k, only IE browser supports it.

Goal

  1. Solve the size problem of 4k

  2. Solve the problem that request headers often carry storage information Problem

  3. Solving the problem of relational storage

  4. Cross-browser

##1. Local storage localstorage

Storage method:

Key-Value Storage method, permanent storage, never expires unless manually deleted.

Size:

5M per domain name

Support:

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');
}

Commonly used API:

getItem //Get the record

setIten//Set the record

removeItem//Remove the record

key//Get the value corresponding to the key

clear //Clear the record

Stored content:

array, picture, json, style, script . . . (As long as the content can be serialized into a string, it can be stored)

2. Local storage sessionstorage

In the local storage API of HTML5 The usage methods of localStorage and sessionStorage 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)

Local cache of files required by the application

How to use:

①Configure manifest file

On page:

nbsp;HTML>

...

Manifest file:

Manifest files are simple text files that tell the browser what is cached (and what is not cached).

The manifest file can be divided into three parts:

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

②NETWORK - under this heading The outgoing files require a connection to the server and will not be cached

③FALLBACK - The files listed under this heading specify the fallback page (such as a 404 page) when the page cannot be accessed

Complete demo:

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

On the server: 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>

Commonly used API:

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

0 (UNCACHED): No cache, that is, there is no application cache associated with the page

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

2 (CHECKING) : 检查中,即正在下载描述文件并检查更新

3 (DOWNLOADING) : 下载中,即应用缓存正在下载描述文件中指定的资源

4 (UPDATEREADY) : 更新完成,所有资源都已下载完毕

5 (IDLE) :  废弃,即应用缓存的描述文件已经不存在了,因此页面无法再访问应用缓存

 相关的事件:

表示应用缓存状态的改变:

checking : 在浏览器为应用缓存查找更新时触发

error : 在检查更新或下载资源期间发送错误时触发

noupdate : 在检查描述文件发现文件无变化时触发

downloading : 在开始下载应用缓存资源时触发

progress:在文件下载应用缓存的过程中持续不断地下载地触发

updateready : 在页面新的应用缓存下载完毕触发

cached : 在应用缓存完整可用时触发 

Application Cache的三个优势:

① 离线浏览

② 提升页面载入速度

③ 降低服务器压力

注意事项:

1. 浏览器对缓存数据的容量限制可能不太一样(某些浏览器设置的限制是每个站点 5MB)

2. 如果manifest文件,或者内部列举的某一个文件不能正常下载,整个更新过程将视为失败,浏览器继续全部使用老的缓存

3. 引用manifest的html必须与manifest文件同源,在同一个域下

4. 浏览器会自动缓存引用manifest文件的HTML文件,这就导致如果改了HTML内容,也需要更新版本才能做到更新。

5. manifest文件中CACHE则与NETWORK,FALLBACK的位置顺序没有关系,如果是隐式声明需要在最前面

6. FALLBACK中的资源必须和manifest文件同源

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('mydb', '1.0', 'Test DB', 2 * 1024 * 1024,fn);
//openDatabase() 方法对应的五个参数分别为:数据库名称、版本号、描述文本、数据库大小、创建回调

执行查询操作:

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)');
});

插入数据: 

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")');
});

读取数据:

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 <p style="text-align: left;">由这些操作可以看出,基本上都是用SQL语句进行数据库的相关操作,如果你会MySQL的话,这个应该比较容易用。</p><p style="text-align: left;"><strong><span style="color:#ff0000">5.IndexedDB</span></strong></p><p style="text-align: left;">索引数据库 (IndexedDB) API(作为 HTML5 的一部分)对创建具有丰富本地存储数据的数据密集型的离线 HTML5 Web 应用程序很有用。同时它还有助于本地缓存数据,使传统在线 Web 应用程序(比如移动 Web 应用程序)能够更快地运行和响应。</p><p style="text-align: left;"><strong><span style="color:#3366ff"> 异步API:</span></strong></p><p style="text-align: left;">在IndexedDB大部分操作并不是我们常用的调用方法,返回结果的模式,而是请求——响应的模式,比如打开数据库的操作</p><p style="text-align: left;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/d57e81a779eb97584a313180315c4be6-2.png?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><p   style="max-width:90%">这样,我们打开数据库的时候,实质上返回了一个DB对象,而这个对象就在result中。由上图可以看出,除了result之外。还有几个重要的属性就是onerror、onsuccess、onupgradeneeded(我们请求打开的数据库的版本号和已经存在的数据库版本号不一致的时候调用)。这就类似于我们的ajax请求那样。我们发起了这个请求之后并不能确定它什么时候才请求成功,所以需要在回调中处理一些逻辑。</p><p style="text-align: left;"><strong><span style="color:#3366ff">关闭与删除:</span></strong></p><pre class="brush:php;toolbar:false">function closeDB(db){
     db.close();
}
function deleteDB(name){
     indexedDB.deleteDatabase(name);
}

数据存储:

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

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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

H5实现旋转立体魔方

spring mvc+localResizeIMG实现H5端图片压缩上传

The above is the detailed content of Detailed explanation of H5 storage method. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.