Editor’s recommendation: This article comes from Hacker Magazine. It provides a very comprehensive introduction and analysis of this storage method of HTML5. For developers who are learning HTML5, it is not to be missed.
HistoryBefore HTML5 local storage, if we wanted to save persistent data on the client, we had several options:
HTTP cookie. The disadvantages of HTTP cookies are obvious, they can only store up to 4KB of data, and each HTTP request will be transmitted back to the server in clear text (unless you use SSL).
IE userData. userData is a local storage solution launched by Microsoft during the browser wars of the 1990s. It uses the behavior attribute of DHTML to store local data. It allows each page to store up to 64K data and each site to store up to 640K data. The shortcomings of userData are obvious. It's not part of the web standards, so unless your application only needs to support IE, it's of little use.
Flash cookie. The name of Flash cookie is a bit misleading. It is actually not the same thing as HTTP cookie. Maybe its name should be called "Flash local storage". Flash cookie allows each site to store no more than 100K of data by default. If it exceeds, Flash It will automatically request more storage space from the user. With the help of Flash's ExternalInterface interface, you can easily operate Flash's local storage through Javascript. The problem with Flash is simply that it is Flash.
Google Gears. Gears is an open source browser plug-in released by Google in 2007, aiming to improve the compatibility of major browsers. Gears has a built-in embedded SQL database based on SQLite and provides a unified API to access the database. After obtaining users After authorization, each site can store data of any size in the SQL database. The problem with Gears is that Google itself no longer uses it.
Current situationWhat we usually call HTML5 local storage now generally refers to Web
Storage specification, this standard was once part of the HTML5 specification, but was later separated from the HTML5 specification for various reasons. But in addition to Web Storage, there are two other competitors for HTML5's local storage standard: Web SQL Database and IndexedDB. Let us take a look at these 3 specifications in turn.
Web StorageWeb Storage is currently the most widely supported HTML5 local storage specification: IE 8, FF 3.5, Safari 4, Chrome 4, Opera 10.5, and iPhone 2 and Android 2 already supports Web Storage. To determine whether your browser supports Web Storage, you can use the following function:
Code
function supports_html5_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } }
HTML5 Storage is very simple to use:
Code
var foo = localStorage.getItem("bar"); // ... localStorage.setItem("bar", foo);
你也可以写成下面这样:
代码
var foo = localStorage["bar"]; // ... localStorage["bar"] = foo;
如果要将某个key从存储空间删除,可以调用removeItem:
代码
localStorage.removeItem( 'foo' );
你也可以像遍历数组那样遍历存储的所有键值对象:
代码
for(var i=0; ivar key = localStorage.key(i); console.log(key + ":" + localStorage[key]); }
如果你的程序需要在不同页面访问同一个值,你可能需要了解这个值是否已经被其他页面改变了,这可以通过向浏览器注册storage事件来实现:
代码
window.addEventListener('storage', function(e) { console.log(e.key + "'s value is changed from '" + e.oldValue + "' to '" + e.newValue + "' by " + e.url); }, false); //A页面 localStorage['foo'] = 'bar'; //B页面 localStorage['foo'] = 'newBar';
这时你应该会在A页面的Console中看到:
foo’s value is changed from ‘bar’ to ‘newbar’ by http://localhost/test.html
要注意的是,storage事件仅仅只是通知你某个键对应的值已经发生了改变,你没有办法在回调中阻止这个改变发生。
HTML5 Storage看起来不错,那它有没什么缺点呢?好问题。要说HTML5 Storage的缺点,唯一的问题就是它默认的QUOTA只有5MB,并且你没办法通过程序自行或是提示用户来增加存储空间。唯一的办法就是用户自己打开 浏览器的设置,并手动修改QUOTA的大小,如果超出了5MB的限制,你将会遇到一个“QUOTA_EXCEEDED_ERR”的错误。
Web SQL DatabaseWeb SQL Database是一个已经废弃的规范,但是鉴于除了IE和Firefox,其他浏览器都已经实现了Web SQL Database,并且它还具有一些HTML5 Storage所不具有的特性,所以还是值得了解一下的。
Web SQL Database就像它的名字那样,就是一个让你可以在Web上直接使用的SQL数据库,你要做的就是打开数据库,然后执行SQL,和你对Mysql做的事情没什么两样:
代码
openDatabase('documents', '1.0', 'Local document storage', 5*1024*1024, function (db) { db.changeVersion('', '1.0', function (t) { t.executeSql('CREATE TABLE docids (id, name)'); }, error); });
关于Web SQL Database的更多介绍,可以参看这篇指南。
但是它的缺点也同样明显。最大的问题就出在SQL上,实际上并不存在一种叫做SQL的标准结构化查询语言,我们平常使用的实际上是MS SQL、Oracle SQL、MySQL SQL、postgre SQL或者SQLite SQL(尽管有一个叫做SQL-92的规范,但它基本形同虚设),更进一步,甚至都不存在SQLite
SQL,我们使用的实际上是SQLite x.y.z SQL,而这也就是Web SQL Database最大的问题,它无法统一各个浏览器厂商实现的SQL语言,如果你的某条Web SQL查询只能在Chrome上运行,这还能叫做标准吗?
所以,如果你现在访问Web
SQL Database的规范页面,你会在顶部看到这样一则声明:
这个规范已经陷入了一个僵局:目前的所有实现都是基于同一个SQL后端(SQLite),但是我们需要更多的独立实现来完成标准化,所以除非有厂商愿意独立实现这个规范,否则当前的SQL规范只能采用SQLite的SQL方言,而作为一个标准,这是不可接受的。
IndexedDB最后我们要介绍的就是IndexedDB了,相比其他两个规范,目前只有Firefox实现了IndexedDB(顺便提一下,Mozilla表示它们永远不会去实现Web
SQL Database),不过Google已经表示正在考虑在Chrome中加入IndexDB支持。
IndexedDB引入了一个object store的概念,这有点像是一个SQL Database,你可以在“数据库”中存储“记录”,并且每条“记录”可以拥有很多“字段",每个字段都有一个特定的数据类型,你可以选择记录的子集, 并使用“光标”进行遍历,同时object store中的所有变更都是基于“事务”的。
下面让我们来看一个小例子:
代码
var request = window.indexedDB.open("CandyDB", "My candy store database"); request.onsuccess = function(event) { var db = event.result; if (db.version != "1") { // User's first visit, initialize database. var createdObjectStoreCount = 0; var objectStores = [ { name: "kids", keyPath: "id", autoIncrement: true }, { name: "candy", keyPath: "id", autoIncrement: true }, { name: "candySales", keyPath: "", autoIncrement: true } ]; function objectStoreCreated(event) { if (++createdObjectStoreCount == objectStores.length) { db.setVersion("1").onsuccess = function(event) { loadData(db); }; } } for (var index = 0; index < objectStores.length; index++) { var params = objectStores[index]; request = db.createObjectStore(params.name, params.keyPath, params.autoIncrement); request.onsuccess = objectStoreCreated; } } else { // User has been here before, no initialization required. loadData(db); } };
关于Indexed的更多介绍可以参看Mozilla Blog的这篇指南。
本文讲解了关于HTML5本地存储的相关内容,更多相关内容请关注php中文网。
相关推荐:
Explanation on the php Captcha verification code class
##MySQL information_schema related content
View mysql database size, table size and last modification time
The above is the detailed content of Related explanations about HTML5 local storage. For more information, please follow other related articles on the PHP Chinese website!

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.

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.

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.

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

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.

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
