search
HomeWeb Front-endH5 TutorialSummary of HTML5 storage methods

Summary of HTML5 storage methods

Jan 11, 2018 pm 04:22 PM
h5html5

This article mainly shares with you a summary of HTML5 storage methods. I hope it can help HTML5 developers and help everyone better master HTML5 storage methods.
  1. The Savage Growth of Cookies

  2. Local Storage localstorage

  3. Local Storage sessionstorage

  4. Offline cache (application cache)

  5. Web SQL

  6. IndexedDB

The barbaric growth of Cookies

Before HTML5 appeared, Cookies occupied the entire world of client storage, just like the barbaric growth of the barbaric era. cookiesMeet the needs of practical applications well and quickly. But its problems are also obvious. cookies will carry data in the request header, and the size is limited to 4K, which is very unsafe and easy to be intercepted by the outside. There are also domainpollute.

IE The browser especially likes to create its own set. To increase the storage capacity, UserData is added. The size is 64K, but other browsers The computer doesn't like to play with it, so it is the only one that supports it.

Then, here comes the point. Since there are so many problems with cookies, we must find ways to solve them, otherwise we will not be able to move forward. First identify its problems and then find solutions based on those problems.

  • Solve 4KStorage capacity problem

  • Solve the problem of request headers with storage information, which is to increase security , data storage and transmission through encrypted channels or methods

  • Solving the problem of relational storage

  • Cross-browser

Local storage localstorage

Storage method

Stored in the form of key-value pairs, permanently stored, and will never expire unless Delete manually.

Storage capacity

5M per domain name.

Commonly used API

getItem //Get the record

setItem //Set the record

removeItem //Remove the record

key //Get the value corresponding to key

clear //Clear the record

Local storage sessionstorage

Local storage of HTML5localstorage# in API ## and sessionstorage are the same in usage. The difference is that sessionstorage will be cleared after closing the page, while localstorage will always be saved unless manually delete. Offline cache (application cache)

Local cache files required by the application

Usage method

1. Configuration

manifest

FileOn page:

nbsp;HTML>

...

manifestFile:

manifest

Is the simplest text file that tells the browser what is cached (and what is not cached).

manifestThe file is divided into three parts:

  1. CACHE MANIFEST

    - In this title The files listed below will be cached after the first download

  2. NETWOrK

    - Files under this heading require a connection to the server and will not be cached

  3. FALLBACK

    - The files under this heading specify the fallback 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.js

NETWORK:
login.jsp

FALLBACK:
/html/ /offline.html

On the server:

manifest file needs to be configured correctly MIME-type, which is text/cache-manifest.

Commonly used

APIThe core is the

applicationCache

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

0 (UNCACHED)

: No cache, no application cache related to the page

1 (IDLE)

: Idle , the application cache has not been updated

2 (CHECKING)

: Checking, downloading the description file and checking for updates

3 (DOWNLOADING)

: Downloading, the application cache is downloading the resources specified in the description file

4 (UPDATEREADY)

: The update is completed, all resources have been downloaded

5 (IDLE)

: Abandoned, the application cache description file no longer exists, so the page can no longer access the application cache

Related events

indicates the application cache status Changes to:

checking

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

error

: An error occurred during checking for updates or downloading a resource Triggered when

noupdate

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

downloading

: Triggered when starting to download application cache resources

progress

: Triggered when the file download application cache continues to download

updateready

: Triggered when the new application cache download of the page is completed

cached

: Triggered when the application cache is fully available

Three advantages of application cache:

  1. 离线浏览

  2. 提升页面载入速度

  3. 降低服务器压力

注意事项:

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

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

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

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

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

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

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

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

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

离线缓存和传统浏览器缓存的区别

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

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

Web SQL

Web SQL数据库API并不是HTML5规范的一部分,但它是一个独立的规范,引入了一组使用SQL操作客户端数据库的APIs

核心方法

  1. openDatabase:使用现有的数据库或新建的数据库创建一个数据库对象

  2. transaction: 控制一个事务,以及基于这种情况执行提交或回滚

  3. executeSql:用于执行实际的SQL查询

打开数据库

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

执行查询操作

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")');
});
注:需要实现的代码块样式,这个是 markdowpad2 里的操作,也是很多markdown写作工具提供的操作,只需要按一下 tab 键,非常方便
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 <h2 id="IndexedDB">IndexedDB</h2><p>索引数据库(<code>IndexedDB</code>)<code>API</code>(作为<code>HTML5</code>的一部分)对创建具有丰富本地存储数据的数据密集型的离线<code>HTML5 Web</code>应用程序很有用,同时它还有助于本地缓存数据,使传统在线<code>Web</code>应用程序(比如移动<code>Web</code>应用程序)能够快速的运行和响应。</p><p><strong>异步<code>API</code></strong></p><p>在<code>IndexedDB</code>大部分操作并不是我们常用的调用方法(返回结果的模式),而是(请求-响应模式),比如打开数据库的操作。</p><p>相关推荐:</p><p><a href="http://www.php.cn/html5-tutorial-361331.html" target="_self">前端HTML5几种存储方式的总结</a></p><p><a href="http://www.php.cn/js-tutorial-340047.html" target="_self">JavaScript中变量的存储方式</a></p><p><a href="http://www.php.cn/php-weizijiaocheng-302975.html" target="_self">在PHP中自定义session的存储方式_PHP教程</a></p><p class="comments-box-content"><br></p>

The above is the detailed content of Summary of HTML5 storage methods. 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: 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.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!