HTML5 storage method


Since I was often asked about the contents stored in HTML5 during the interview or written examination before, including their differences, characteristics and application scope, I saw a good introduction article and summarized the contents that the individuals felt fit for me according to my own understanding as follows. For convenience, I forgot to check it later.

Original link:HTML5 5 summary of major storage methods

  1. The barbaric growth of Cookies
  2. Localstorage
  3. Local storage sessionstorage
  4. Application cache
  5. Web SQL
  6. IndexedDB

The barbaric growth of Cookies

InHTML5Before it appeared,CookiesIt occupies the whole country of client storage, just like the barbaric growth in the barbaric era.cookiesIt can meet the needs of practical application very well and quickly. But its problems are also obvious.cookiesThe data will be carried on the request header, and the size is limited to 4K, which is very unsafe, easy to be intercepted by the outside, and still exists.domainPollution.

IEBrowsers especially like to make their own set, adding to increase storage capacityUserData, the size is64K, but other browsers don’t like to play with it, and only its own support.

So, here’s the point. SincecookiesThere are so many problems, we must find ways to solve them, otherwise we cannot continue to develop. First of all, we should confirm what its problems are, and then find solutions according to these problems.

  • Solve4KStorage capacity problem
  • To solve the problem that the request header has stored information, that is, to increase security, data storage and transmission are carried out through encrypted channels or methods.
  • Solving the Problem of Relational Storage
  • Cross browser


Storage method

Stored as a key-value pair, permanently stored and never invalidated unless manually deleted.

Storage capacity

Each domain name5M.

Common apis

getItem//Take Records

setItem//Set Record


key//TakekeyThe corresponding value

clear//Clear Records

Local storage sessionstorage

HTML5Local storage ofAPIhit the targetlocalstorageAndsessionstorageThe use method is the same except thatsessionstorageAfter closing the page, it is emptied, andlocalstorageIt will be saved until manually deleted.

Application cache

Locally cache files required by the application

Use method

1. ConfigurationmanifestFile

On the page:

<html manifest="demo.appcache">


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

manifestThe document is divided into three parts:

  1. CACHE MANIFEST-Files listed under this heading will be cached after the first download.
  2. NETWOrK-Files under this heading need to be connected to the server and will not be cached.
  3. FALLBACK-Files under this heading specify a fallback page when the page cannot be accessed (e.g.404Page)


# 2016-07-24 v1.0.0


/html/ /offline.html

On server:manifestFiles need to be configured correctlyMIME-type, i.e.text/cache-manifest.


The core isapplicationCacheObject, there isstatusProperty that represents the current state of the application cache:

0 (UNCACHED): No cache, no page-related application cache

1 (IDLE): Idle, Application Cache Not Updated

2 (CHECKING): checking, downloading description file and checking for updates

3 (DOWNLOADING): during download, the application cache is downloading and describing the resources specified in the file

4 (UPDATEREADY): update completed, all resources have been downloaded

5 (IDLE): Obsolete, the description file of the application cache no longer exists, so the page can no longer access the application cache

Related events

Indicates a change in the application cache state:

checking: Triggered when the browser looks for updates for the application cache

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

noupdate: Triggered when checking the description file and finding no change in the file

downloading: Triggered when downloading application cache resources starts

progress: Triggered when the file download application cache is continuously downloaded during file download

updateready: Triggered when the page’s new application cache is downloaded

cached: Triggered when the application cache is fully available

application cacheThree advantages of:

  1. Browse offline
  2. Improve page loading speed
  3. Reduce server pressure


  1. Browsers may have different capacity limits for cached data (some browsers set limits for each site5M)
  2. If it ismanifestThe file, or one of the internal listed files, cannot be downloaded normally. The whole update process will be regarded as a failure, and the browser will continue to use the old cache.
  3. QuotemanifestThehtmlMust be related tomanifestThe files are homologous and under the same domain.
  4. The browser automatically caches referencesmanifestdocumentaryhtmlFile, which leads to if changedhtmlContent, also need to update the version to be up to date
  5. manifestIn the fileCACHEAndNETWOrKFALLBACKThe position order of the is irrelevant, if it is implicit declaration, it needs to be at the front.
  6. FALLBACKResources in must matchmanifestFile homology
  7. After updating the version, it must be refreshed once before starting the new version (there will be a case of re-brushing the page), and a listening version event needs to be added.
  8. Even if other pages in the site are not set upmanifestProperty, if the requested resource is also accessed from the cache
  9. WhenmanifestWhen a file changes, the resource request itself also triggers an update

The difference between offline cache and traditional browser cache

  1. Offline caching is for the entire application and browser caching is a single file
  2. Offline caching can actively notify browsers to update resources


Web SQLDatabaseAPINot reallyHTML5Part of the specification, but it is an independent specification that introduces a set of usesSQLThe that operates the client databaseAPIs.

Core approach

  1. openDatabase: Creates a database object using an existing database or a newly created database
  2. transaction: Controls a transaction and performs commit or rollback based on this condition
  3. executeSql: Used to perform actualSQLQuery

Open database

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

Execute query operation

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

Insert data

Note: Code Block Styles in Blog Topics

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

Note: The code block style to be implemented, this is the operation in markdowpad2, and it is also the operation provided by many markdown writing tools. Just press tab, which is very convenient.

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

Read data

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 < len; i++){
         alert(results.rows.item(i).name );

   }, null);


Index database (IndexedDB)API(as)HTML5Part of) to create a data intensive offline with rich locally stored dataHTML5 WebThe application is very useful, and it also helps to cache data locally, making traditional onlineWebApplications (such as mobileWebApplications) can run and respond quickly.


InIndexedDBMost of the operations are not our usual calling methods (the mode of returning results), but (the request-response mode), such as the operation of opening the database.