From: Small Mosquito-blog Park
Links: http://www.cnblogs.com/LuckyWinty/p/5699117.html
Overall situation
Prior to H5, storage was primarily made with cookies. Cookie disadvantage has the data on the request head, the size is within 4k. Primary domain pollution.
main applications: shopping cart, customer Login
For IE browser has userdata, size is 64k, only IE browser support.
Goal
Solve the 4k size problem
Solve the problem of the request header often with storage information
Solve the problem of relational storage
Cross-browser
1. Local Storage Localstorage
Storage mode:
Stored as a key-value pair (key-value), permanently stored, and never invalidated unless manually deleted.
Size:
5M per domain
Support situation:
Note: IE9 Localstorage does not support local files, it needs to be the project to the server, to support!
Detection method:
if(window.localStorage){ alert(‘This browser supports localStorage‘); }else{ alert(‘This browser does NOT support localStorage‘); }
Common APIs:
GetItem//Fetch Records
setiten//Setting record
removeitem//Removing records
key//the value corresponding to the key
clear//Clearing Records
What's stored:
arrays, images, JSON, styles, scripts ... (only content that can be serialized into strings can be stored)
2. Local Storage Sessionstorage
The localstorage in the HTML5 local storage API is the same as sessionstorage in the usage method, except that Sessionstorage is emptied after the page is closed, and Localstorage is saved.
3, offline cache (application cache)
Files required for the local cache app
How to use:
① Configuring Manifest files
On the page:
<html manifest="demo.appcache"> ... </html>
Manifest file:
The manifest file is a simple text file that tells the browser what to cache (as well as 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-Files listed under this heading require a connection to the server and are not cached
③fallback-Files listed under this heading provide a fallback page when the page is inaccessible (e.g. 404 pages)
Full Demo:
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, which is "text/cache-manifest".
such as Tomcat:
<mime-mapping> <extension>manifest</extension> <mime-type>text/cache-manifest</mime-type> </mime-mapping>
Common APIs:
The core is the Applicationcache object, which has a status property that represents the current state of the app cache:
0 (uncached): No cache, no page-related app cache
1 (Idle): idle, that is, the app cache has not been updated
2 (CHECKING): Check that the profile is being downloaded and check for updates
3 (Downloading): downloaded, that is, the application cache is downloading the resource specified in the profile
4 (Updateready): Update complete, all resources have been downloaded
5 (IDLE): Obsolete, that is, the application cache description file no longer exists, so the page can not be revisited
Ask the app cache
Related events:
Represents a change in the application cache state:
checking: triggered when the browser looks for updates for the app cache
Error : triggered when an error is sent while checking for updates or downloading resources
noupdate: triggers when checking the description file for no changes to the file
downloading: triggered when the app cache resource is started downloading
progress: continuously download and trigger during file download application cache
Updateready: trigger on page new app cache download completed
cached: triggers when the application cache is fully available
Three benefits of application cache:
① Offline Browsing
② Boost page load speed
③ Reduce server pressure
Precautions :
1. Browser capacity limits for cached data may not be the same (some browser settings are limited to 5MB per site)
2, if the manifest file, or the internal enumeration of a file can not be downloaded properly, the entire update process will be considered a failure, the browser continues to use all the old cache
3, the HTML reference manifest must be the same as the manifest file, under the same domain
4. The browser automatically caches the HTML file that references the manifest file, which results in the need to update the version if the HTML content is changed.
5. The cache in the manifest file has no relation to the position order of the network,fallback, if the implicit declaration needs to be in the front
6, the resources in the fallback must and the manifest file homologous
7, after the update version, you must refresh the new version will be started (the situation will occur when the page is re-brushed), you need to add a listener version of the event.
8. Other pages in the site if the manifest property is not set, the requested resource is also accessed from the cache in the cache
9, when the manifest file changes, the resource request itself will trigger the update
Click to see more information!
Offline caching differs from traditional browser caching:
1, offline cache is for the entire application, browser cache is a single file
2, offline cache off the network or can open the page, browser cache does not
3, offline cache can proactively notify the browser to update resources
4. Web SQL
relational database, accessed through SQL statements
The Web SQL database API is not part of the HTML5 specification, but it is a separate specification that introduces a set of APIs that use SQL to manipulate the client database.
Support situation:
Web SQL Database works in the latest version of Safari, Chrome, and Opera browsers.
Core approach:
①opendatabase: This method creates a database object using an existing database or a newly created database.
②transaction: This method allows us to control a transaction and execute commits or rollbacks based on this condition.
③executesql: This method is used to execute the actual SQL query.
Open the database:
var db = openDatabase(‘mydb‘, ‘1.0‘, ‘Test DB‘, 2 * 1024 * 1024,fn); //openDatabase() 方法对应的五个参数分别为:数据库名称、版本号、描述文本、数据库大小、创建回调
To perform a 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:
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); });
As can be seen from these operations, basically all the database with SQL statements related operations, if you can MySQL, this should be easier to use.
Click I see more Tutorials!
5, IndexedDB
The index Database (IndexedDB) API (as part of HTML5) is useful for creating data-intensive offline HTML5 WEB applications that have rich, locally stored data. It also helps to cache data locally, enabling traditional online Web applications, such as mobile Web applications, to run and respond faster.
Asynchronous API:
Most operations in INDEXEDDB are not our usual method of calling, returning the result of a pattern, but rather a request-response pattern, such as opening a database operation
Thus, when we open the database, we essentially return a DB object, and this object is in result. As can be seen, in addition to the result. There are also several important properties called OnError, onsuccess, onupgradeneeded (the version number of the database that we requested to open and the version number of the database that already exists). This is similar to our AJAX request. After we have initiated this request, we are not sure when it will be successful, so we need to deal with some logic in the callback.
Close and Delete:
function closeDB(db){ db.close(); } function deleteDB(name){ indexedDB.deleteDatabase(name); }
Data storage:
INDEXEDDB does not have the concept of a table, but ObjectStore, a database can contain multiple objectstore,objectstore is a flexible data structure, can hold multiple types of data. In other words, a objectstore is equivalent to a table, and each piece of data stored in it is associated with a single key.
We can use one of the specified fields in each record as the key value (KeyPath), or we can use the auto-generated increment number as the key value (Keygenerator), or we can not specify it. There are differences in the data structures that ObjectStore can store, depending on the type of selection key.
This is a little bit more complicated. See the tutorials here:
1, http://www.cnblogs.com/dolphinX/p/3415761.html
2, http://www.cnblogs.com/dolphinX/p/3416889.html
Detailed API Address: http://www.ibm.com/developerworks/cn/web/wa-indexeddb/#ibm-pcon
Summary of several storage methods for front-end HTML5