Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of offline Storage and cookie Storage in html5

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you the "example analysis of offline storage and cookie storage in html5", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let me lead you to study and learn the "sample analysis of offline storage and cookie storage in html5".

What is Cookies (cookie)? To put it simply, Cookies is the data (.txt format text file) that the server temporarily stores on your computer so that the server can use it to identify your computer. When you are browsing the website, the Web server will first send a small piece of information to your computer, and Cookies will help you write down the text you type on the site or some choices. The next time you visit the same website, the Web server will first check to see if it has the Cookies information it left last time. If so, it will judge the user based on the content in Cookie and send you specific web content. Before HTML5, we would use cookie to cache some data on the browser side, such as login user information, historical search information, and so on. However, the capacity of cookie is only 4k, and there is no special api to operate, so it can only rely on some open source libraries, where cookies.js is used to store and obtain cookie information.

/ / this is a cookie value Cookies.set ('key',' value'); / / chain call Cookies.set ('key',' value'). Set ('hello',' world'); / / you can set some additional parameters Cookies.set ('key',' value', {domain: 'www.example.com', secure: true}); / / set cache time Cookies.set (' key', 'value', {expires: 600}) / / Expires in 10 minutesCookies.set ('key',' value', {expires: '01new Date 2012'}); Cookies.set ('key',' value', {expires: new Date (0,0,1)}); Cookies.set ('key',' value', {expires: Infinity}); / / get Cookies.get ('key')

This shows that there are several disadvantages to using cookie storage:

The amount of data stored is relatively small.

There is no convenient api to operate it.

Cookie information is added to the request header at the time of the http request, which is both insecure and increases bandwidth.

WEB Storage

HTML5 Tiegong's better local storage specifications, localStorage and sessionStorage, store data locally and do not carry information from Storage when http requests, and are easy to use:

LocalStorage.setItem ('key',' value'); localStorage.getItem ('key'); localStorage.removeItem (' key'); sessionStorage.setItem ('key',' value'); sessionStorage.getItem ('key'); sessionStorage.removeItem (' key')

The usage and features of sessionStorage and localStorage are basically the same, except that sessionStorage is only valid within the session. When the browser window is closed, the data cached by sessionStorage will be automatically cleared, while localStorage will be permanently saved locally as long as it is not manually cleared.

Here is a picture that analyzes the differences among cookie, localStorage and sessionStorage.

OFFLINE (offline)

In order to make webapp have the same functionality and experience as native app, many new api have been added to the HTML5 specification so that the page can be accessed normally in an offline environment. Service worker and indexedDB can work together to develop webapp for offline use. As the current compatibility of service worker is not very good, here we write an introduction to the earlier solution application cache.

Service worker

Service Worker is event-driven based on Web Worker, and the mechanism they execute is to open a new thread to handle additional tasks that could not be handled directly before. For Web Worker, we can use it for complex calculations because it does not block the rendering of the browser's main thread. Service Worker, on the other hand, can be used for local caching, which is equivalent to a local proxy. Speaking of caching, we will think of some of our commonly used caching techniques to cache our static resources, but the old way does not support debugging and is not very flexible. Using Service Worker for caching, we can use javascript code to intercept browser http requests, set cached files, return directly, without going through the web server, and then do more things you want to do.

Therefore, we can develop browser-based offline applications. This makes our web applications less dependent on the network. For example, we have developed a web application for news reading. When you open it with a mobile browser and a network, you can get the news content normally. However, if your phone goes into flight mode, you won't be able to use this app.

If we use Service Worker as the cache, the browser http request will first go through Service Worker and match through url mapping. If the match is reached, the cached data will be used. If the match fails, the action you specified will continue. In general, a match failure causes the page to show "the page cannot be opened".

Service work lifecycle

Service work demo

Navigator.serviceWorker.register ("/ service-worker.js") .then (function (serviceWorker) {console.log ("success!");})

This js will be called when the page registers service-worker successfully.

This.oninstall = function (e) {var resources = new Cache (); var visited = new Cache (); / / Fetch them. E.waitUntil (resources.add ("/ index.html", "/ fallback.html", "/ css/base.css", "/ js/app.js", "/ img/logo.png"). Then (function () {/ / Add caches to the global caches. Return Promise.all ([caches.set ("v1", resources), caches.set ("visited", visited)]);});}; this.onfetch = function (e) {e.respondWith (/ / Check to see if request is found in cache caches.match (e.request) .catch (function () {/ / It's not? Prime the cache and return the response. Return caches.get ("visited") .then (function (visited) {return fetch (e.request). Then (function (response) {visited.put (e.request, response); / / Don't bother waiting, respond already. Return response;}) .catch (function () {/ / Connection is down? Simply fallback to a pre-cached page. Return caches.match ("/ fallback.html");};);}

Service worker uses event listening mechanism. The above code listens for install and fetch events. When server worker is installed successfully, call this method, and then cache the page's resource file, fetch page request event, and server worker intercepts the user's request. When the request file is found to hit the cache, the file is taken from the cache and returned to the page without going through the server, thus achieving offline purposes.

Of course, the function of service worker is much more than that now.

IndexedDB

IndexedDB is a nosql database used to store data locally, with extremely fast data query speed, and can save js objects directly. It is more efficient than web sql (sqlite), including indexing, transaction processing, and robust query capabilities. IndexedDB features:

1. A site may have one or more IndexedDB databases, each of which must have a unique name.

two。 A database can contain one or more object stores

An object store (uniquely identified by a name) is a collection of records. Each record has a key and a value. The value is an object that can have one or more properties. The key may be based on a key generator, derived from a key path, or explicitly set. A key generator automatically generates unique consecutive positive integers. The key path defines the path of the key value. It can be a single JavaScript identifier or multiple identifiers separated by periods.

The basic usage is as follows:

Var openRequest = indexedDB.open ("auto_people", 3); var db; / / Database object openRequest.onupgradeneeded = function (e) {console.log ("Running onupgradeeded..."); var thisDB = e.target.result; if (! thisDB.objectStoreNames.contains ("people")) {thisDB.createObjectStore ("people", {autoIncrement:true}) / / create a new store and set the primary key self-growing}} / / successfully created openRequest.onsuccess = function (e) {console.log ("success!"); db = e.target.result; / / Listen for add clicks} openRequest.onerror = function (e) {console.log ("error!"); console.dir (e) } / / this should be handled somewhere else, this is to do a code showing var transaction = db.transaction (['people'], "readwrite"); / / create a connection var store = transaction.objectStore ("people"); / / get storevar request = store.add ({name:' myron', email: 'test@qq.com', created: new Date ()}); / / add information request.onerror = function (e) {alert (' errorship') Console.dir (e);} / / call request.onsuccess = function (e) {console.log ('Did itinerary') when adding fails;} / / call request = store.get (1) when adding succeeds; / / get the first piece of data request.onsuccess = function (e) {var result = e.target.result; console.dir (result) If (result) {/ / get stored objects}} these are all the contents of the article "sample Analysis of offline Storage and cookie Storage in html5". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report