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

Related explanations about HTML5 local storage

jacklove
Release: 2018-06-11 16:59:30
Original
1681 people have browsed it

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:

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

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

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

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

  1. function supports_html5_storage() {  
        try {  
            return 'localStorage' in window && window['localStorage'] !== null;  
        } catch (e) {  
            return false;  
        }  
    }
    Copy after login


HTML5 Storage is very simple to use:

Code

  1. var foo = localStorage.getItem("bar");  
    // ...  
    localStorage.setItem("bar", foo);
    Copy after login


你也可以写成下面这样:

代码

  1. var foo = localStorage["bar"];  
    // ...  
    localStorage["bar"] = foo;
    Copy after login


如果要将某个key从存储空间删除,可以调用removeItem:

代码

  1. localStorage.removeItem(
    'foo'
    );
    Copy after login


你也可以像遍历数组那样遍历存储的所有键值对象:

代码

  1. for(var i=0; ivar key = localStorage.key(i);  
        console.log(key + ":" + localStorage[key]);  
    }
    Copy after login


如果你的程序需要在不同页面访问同一个值,你可能需要了解这个值是否已经被其他页面改变了,这可以通过向浏览器注册storage事件来实现:

代码

  1. 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';
    Copy after login


这时你应该会在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做的事情没什么两样:

代码

  1. 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);  
    });
    Copy after login


关于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中的所有变更都是基于“事务”的。
下面让我们来看一个小例子:

代码

  1. 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);  
      }  
    };
    Copy after login

关于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!

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