Four client-side Web storage solutions with the ability to replace cookies

Source: Internet
Author: User
Tags new set sessionstorage

There are several existing standards that are required to store large amounts of data in a user's Web browser, each with its own advantages, short board, unique standardization status, and browser support levels. However, the actual performance of these standards is superior to the widespread existence of the cookie mechanism.

Today's Web applications start doing a lot of data processing in the client and may even need to complete the task offline. It can be said that client-side data storage plays a vital role in the development of next-generation Web applications.

Until now, however, cookies are still the most common data storage mechanism in the user's browser. If a web app requires repeated access to some data, there are only two ways to choose: either send a request to the server again to get the data, or read the content stored in the cookie.

The cookie mechanism can only provide limited storage space-up to 4K or 4096 bytes-so large amounts of data are split into blocks of 4K size to be managed explicitly and directly.

But this approach is obviously not feasible for storage collaboration and management, so we need to come up with a new set of alternatives.

The ability to tolerate cookies is too weak

The Web browser initially simply uses HTTP and parses the HTML to implement the application's loading of the document content. But shortly thereafter, the first Netscape browser appeared, which satisfies a set of real-world needs of the user, but requires the use of essentially stateless HTTP protocols to implement state tracking through certain mechanisms. In the face of this problem, Lou Montulli created a browser cookie (formerly known as the ' Magic Cookie ') in 1994 and was first unveiled on the 0.9b version of the Mosiac Netscape browser.

With the help of the server-side scripting Access function and cookies provided by the Universal Gateway Interface (CGI), the earliest Web application finally became a reality. In the end, we started to turn the browser into a common application platform along this path.

However, there are serious flaws in the cookie mechanism. As mentioned earlier, it can only store a very small amount of data and is susceptible to various types of attack, which makes it difficult to use it to store personal information and sensitive data, which greatly limits its scope of use.

Cookies are involved in every HTTP request sent from the browser to the server side. Suppose a Web page contains four images, an external CSS document, and a JavaScript document. A 4K cookie is set for the domain, and the browser forwards the cookie to the server four times-once for the HTML page, once for each picture, once for the CSS document, and once for the JavaScript document.

The problem is further compounded by the fact that the 4K cookie is theoretically transmitted from the browser to the server side, since most users are using an asynchronous Internet connection that is slower than the download speed, Therefore, transmitting cookie data in the HTTP response header must cause unnecessary bandwidth consumption.

Because of these limitations, most cookies are much smaller than 4 K in volume. Google recommends that the actual size of each cookie not exceed 400 bytes (or 200 characters) for optimal performance. They also suggest that static files from unique domains such as images, CSS, and JavaScript should disable the cookie mechanism.

Because of the many problems of the cookie mechanism in the local storage field, there are a series of new solutions, which aim to complete the task in order to get the right quality and quantity. In recent months, two programs have been on track and highly recommended by the web-they can be good, even better than we expected, to help browsers support local storage capabilities.

Currently we can choose from four main client data storage mechanisms: Web SQL, IndexedDB, Web Storage, and application Cache. We will review each package one by one and explore their respective characteristics in terms of operation and effectiveness.

Web SQL: Good at (but is it somewhat outdated?) ) Database creation and execution

Web SQL is an API that uses a database for data storage and uses SQL to process retrieval tasks. Recently, well-known browsers such as Safari, Chrome, and opera have chosen the former for the competition between Web SQL and INDEXEDDB. At 2010, however, SQLite was the only one by one database capable of collaborating with Web SQL, and the consortium stopped supporting it for a less-than-installation rationale.

The working mechanism of WEB SQL is quite novel, so let's look at the sample code together.

The use of Web SQL database is very similar to relational database and SQL. The first step in using this database is to create and open it. If you do not want to create an additional set of databases, you can start using them directly, and the API itself will automatically complete the creation process.

Let's look at some of the code for database creation:

    1. var db = OpenDatabase (' Cats ', ' 1.0 ',
    • ' A catalog of my cats '

, 2 *1024 * 1024);

In order from left to right, the parameters after OpenDatabase represent the database name, the version number, the text description, and the expected database size.

Once the database is created, you can start using it. Executing SQL on the Websql database is as simple as creating a transactional object and executing it:

    1. Db.transaction (

function

(TX) {

    • Tx.executesql (' CREATE TABLE cats (id unique, name) '

);

    • Tx.executesql (' INSERT into cats (id,name) VALUES (1, "" Mr Jones ") '

);

    • });

Although the API is supported by Safari, Chrome, Opera, and Mobile Safari, there has been no change in Web SQL since 2010, so it is unlikely to be the new standard for local storage.

Web Storage: Take the cookie's director, cookies are short

Web storage uses a simple way to store key/value pairs in a user's browser. But the similarities between it and cookies are just that.

• Web Storage is a set of durable solutions. Once a value has been stored, it will no longer disappear or terminate unless explicitly deleted by the application or user.

• Web Storage can handle large amounts of data. The overall storage area of the browser is currently up to 5MB in size.

The • Web Storage does not have to rely on the server, and it does not have to send data to the server. Of course, you can easily localize the data store and synchronize it with the server asynchronously, but the performance of the Web Storage is always excellent and takes effect both offline and online.

• Web Storage provides four main methods--getitem (key), SetItem (key, value), RemoveItem (key), and clear ().

Finally, the Web storage contains two completely different types of storage: Sessionstorage and Localstorage.

The purpose of Sessionstorage is to ensure that the data stored in the current browser window is used only for that window. For example, when you use e-commerce applications, the use of Sessionstorage to record the user's shopping cart information can avoid the wrong operation of the two purchase situation.

Let's take a look at Localstorage, which is dedicated to saving data that can be used to both Windows and tags that work in the same browser. So if you open three windows on the same website in Chrome, then all three can use the same set of localstorage containers together. In contrast, if we open three web windows with separate content, each will use a separate container. Similarly, if you open the same Web site in a different browser, each browser needs to use its own container, and therefore cannot share the same set of common operating environments.

To set up and retrieve a new set of key-value pairs, you can use the following JavaScript commands:

    1. First set FirstName equal to Sparky.
    • Localstorage.setitem ("FirstName"

,

"Sparky"

);

    • Next, get the value of FirstName (hint, it'll be sparky).

    • Localstorage.getitem ("FirstName"

);

This summer, the Web Storage API officially won the award for the recommended standard. Looking to the future, WEB storage is entirely likely to become a new treatment on the stage where all the original cookies work.

But the Web storage can do a lot more. If the data set is not too large, Web storage also offers another possible easiest way to do it-even easier than cookies-to successfully set up and retrieve key-value pairs in the browser.

IndexedDB: Searchable and no file size restrictions exist

Indexed database is an API that uses indexed transactional databases to save and index data on a user's computer. INDEXEDDB results in faster, more sophisticated data storage and retrieval, with simple key-value-to-storage cookies and Web storage that can only be beats me.

Like Web Storage, the IndexedDB API has taken a big step towards web standards this summer (July 2013) as part of the list of candidate recommendations.

Compared with Web Storage, INDEXEDDB brings four specific improvements:

    1. Ability to efficiently search indexed data.
    • A database can save multiple values as a single key, while a key-value mechanism requires that each key must be unique.
    • transactional databases provide a number of protection measures against system and application failures. If the transaction process fails to complete properly, the recovery is performed by rolling back.
    • The INDEXEDDB database does not limit the size of the data content. In Firefox, the browser will require permissions to increase the capacity of the database to more than 50MB, while INDEXEDDB's actual data storage limits directly depend on the volume limit of the sub-volumes or disk drives themselves.

INDEXEDDB is already supported in all major browsers except Safari. However, because Safari supports Web SQL, we can fully utilize the INDEXEDDB mezzanine (or called shim) to implement INDEXEDDB functionality and syntax through Web SQL.

To use INDEXEDDB, the first step is to open a set of databases.

    1. Var

Request = Indexeddb.open (

"MyDatabase"

);

After the database is created, you can create a storage object (very similar to a table) and add data to it. Suppose we need to add the following data to it:

    • Const PETDATA = [
    • {ID: "00-01"

, FirstName:

"Butters"

, Age:2, type:

"Dog"

},

    • {ID: "00-02"

, FirstName:

"Sammy"

, Age:2, type:

"Dog"

}

    • ];

Next, we can create a data storage mechanism and use it through the following code. Notice how onupgradeneeded is handled: We need to use this approach when changing the database structure.

    1. request.onupgradeneeded =

function

(event) {

    • Var

db = Event.target.result;

    • Var

ObjectStore = Db.createobjectstore (

"Customers"

, {keypath:

"id"

});

    • For

(

Var

I

Inch

CustomerData) {

    • Objectstore.add (Customerdata[i]);
    • }
    • }

INDEXEDDB specializes in searching large database sets and is able to improve the performance of Web applications by moving structured data to clients. It is now very close to the recommended level of the web, and can be used for all browser platforms-although there are differences in how it is implemented, as mentioned earlier, a mezzanine mechanism is required in safari.

Application Cache: Making offline client storage a reality

The application cache is different from the other client data store APIs mentioned earlier, but it is also noteworthy because it has become an important part of offline client Web applications.

Application cache uses a set of cached lists. The so-called list is a very simple text document that lists all the resource entries that should or should not be processed through the caching mechanism, thus directing the browser to download specific files, save them, and use them if necessary-without having to make duplicate requests to the server. All major web browsers currently support the application cache mechanism.

To use application cache, we need to first save a text file with a. appcache extension in the Web site that contains the cached object file. Depending on the specific type of Web server being used, we may need to create a custom MIME type for the. appcache file to ensure that they work correctly in the browser and can be read as an application cache file.

Let's cite a cache list file as an example:

    1. CACHE MANIFEST
    • CACHE:
    • /css/styles.css
    • /js/javascript.css
    • /img/logo.gif
    • FALLBACK:
    • /img/weathertoday.png/img/weathernotavailable.png
    • NETWORK:

Now let's take a detailed reading of the content:

    • The cache section tells the browser which resources need to go into the cache for offline viewing. These files remain in the cache until the cache list changes. It is important to keep this requirement in mind.
    • The fallback section is used to tell the browser which files to display supersede non-cached resources. For example, in the fallback section above, we can speculate that if the latestweather.png image cannot be downloaded correctly, the current weather condition cannot be displayed offline.
    • The network section is used to tell the browser which resources are available only through online mode. The asterisk at the end indicates that there is no network resource present in the cache.

The application cache is an excellent tool that has almost no drawbacks if used properly. In fact, the correct use is a learning: if you simply add all the content on the site to the cache, then visitors will soon find that the site content will never change. If you only keep content that doesn't change frequently in the cache, or try to make sure that the cache list is always up-to-date and publish a new list version as soon as the file is uploaded, the application cache will result in an excellent offline application that is almost as good as the online model.

Local browser Storage has ushered in a major revolution in the past few years. The diverse and similar names used by different APIs and recommended projects make it difficult to figure out what can be used and which should be eliminated in time. All in all, the browser data storage domain has many different ways to choose from, and each one has a very good value for existence.

In any case, the era of developers trying to send a simple small name-value pair to the server via cookies is over. Today, we have more excellent solutions to use.

Four client-side Web storage solutions with the ability to replace cookies

Related Article

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.