Summary of several storage methods in front end

Source: Internet
Author: User
Tags browser cache sessionstorage

Next to a good summary of some knowledge, autumn attracted ... Although there is a lot of knowledge is not the assembly, but still have to work hard, luck this thing, who knows it ~

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 application: Shopping cart, customer login for IE browser has userdata, size is 64k, only IE browser support. The target solves the problem of 4k size problem solving request header often with storage information problems solving relational storage problems 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 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. The localstorage in the local storage API for local storage sessionstorageHTML5 is the same as sessionstorage in the usage method, except that Sessionstorage is emptied after the page is closed and The localstorage will always be saved. 3. Offline cache (application cache) files required for local cache application How to use:① configuration on the manifest file page:
<! DOCTYPE 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:

① CacheMANIFEST -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 -Documents listed under this heading provide a fallback page when the page is inaccessible (e.g. 404 pages)

Full Demo:

CACHE manifest# 2016-07-24 v1.0.0/theme.css/main.jsnetwork:login.jspfallback:/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): deprecated, i.e. the application cache profile no longer exists, so the page cannot access 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 on cached data may not be the same (some browser settings are limited to 5MB per site)
2. If the manifest file, or one of the files listed in the file is not properly downloaded, the entire update process will be considered a failure, the browser continues to use the old cache
3. The HTML that references 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, and if it is implicitly declared it needs to be in the front
6. Resources in fallback must be the same as manifest files
7. After updating the version, you must refresh the new version only once (the situation where the page will be re-brushed) and you need to add a listener version 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 triggers the update

Click to see more information!

Offline caching differs from traditional browser caching:

1. Offline caching is for the entire application, and the browser cache is a single file

2. Offline cache off the screen 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, access to the WEB SQL database API through SQL statements is not part of the HTML5 specification, but it is a separate specification that introduces a set of APIs that use SQL to manipulate client databases.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 * 1024x768 * 1024,FN); the//opendatabase () method corresponds to five parameters: database name, version number, description text, database size, create back Adjustable
To perform a query operation:
var db = OpenDatabase (' mydb ', ' 1.0 ', ' Test db ', 2 * 1024x768 * 1024x768);d b.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 * 1024x768 * 1024x768);d b.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.R Ows.length, I;      msg = "<p> query record number:" + 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!

The 5.IndexedDB Index Database (IndexedDB) API (as part of HTML5) is useful for creating data-intensive offline HTML5 WEB applications with 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 of the operations in INDEXEDDB are not our usual calling methods, but rather the pattern of the request-response, such as the operation to open the database so that when we open the database, we essentially return a DB object, and this object is in the 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 for the time being, it is true that some storage methods have not been used personally, can only find some other people's information. First understand a general, and then use the detailed record it! ^_^

Summary of several storage methods in front end

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.