search
HomeWeb Front-endH5 TutorialHTML5 offline storage and cookie storage analysis

HTML5 offline storage and cookie storage analysis

Nov 18, 2017 pm 01:18 PM
cookiehtml5storage

What are Cookies ("cookies")? To put it simply, cookies are information (text files in .txt format) that the server temporarily stores on your computer so that the server can use it to identify your computer. When you browse a website, the web server will first send a small amount of data to your computer. Cookies will record the text or selections you make on the website. The next time you visit the same website, the web server will first check to see if there is any cookie information it left last time. If so, it will judge the user based on the content in the cookie and send you specific web page content. Before HTML5, we would use cookies to cache some data on the browser side, such as logged in user information, historical search information, etc. However, the capacity supported by cookies is only 4k, and there is no dedicated API for operation. We can only rely on some open source libraries. Cookies.js is used here to store and obtain cookie information.

// 这是一个cookie值Cookies.set('key', 'value');
// 链式调用Cookies.set('key', 'value').set('hello', 'world');
// 可以额外设置一些参数Cookies.set('key', 'value', { domain: 'www.example.com', secure: true });
// 设置缓存时间Cookies.set('key', 'value', { expires: 600 });
// Expires in 10 minutesCookies.set('key', 'value', { expires: '01/01/2012' });
Cookies.set('key', 'value', { expires: new Date(2012, 0, 1) });
Cookies.set('key', 'value', { expires: Infinity });// 获取Cookies.get('key');

It can be seen that using cookie storage has several disadvantages:

The amount of stored data is relatively small

There is no convenient API to operate it

Cookie information will be added to the request header when making an http request, which is both unsafe and increases bandwidth.

WEB Storage

HTML5 provides better local storage specifications localStorage and sessionStorage. They store data locally and do not carry the information in Storage when making http requests. The usage method is also Very simple:

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

sessionStorage and localStorage are basically the same in usage and features. The only difference is that sessionStorage is only valid within the session. When the browser window is closed, the sessionStorage cached data will be automatically cleared, while localStorage only needs If you don't clear it manually, it will be saved locally permanently.

Here is a picture analyzing the differences between cookie, localStorage and sessionStorage

HTML5 offline storage and cookie storage analysis


##OFFLINE(Offline)

In order for the web app to have the same functions and experience as a native app, many new APIs have been added to the HTML5 specification so that the page can be accessed normally in an offline environment. Service worker and indexedDB can be used together to develop webapps for offline use. Since the current compatibility of service workers is not very good, here we will introduce the earlier solution application cache.

service worker

Service Worker is event-driven based on Web Worker. Their execution mechanism is to open a new thread to handle some additional tasks that could not be processed directly before. For Web Worker, we can use it to perform complex calculations because it does not block the rendering of the browser's main thread. As for Service Worker, we can use it for local caching, which is equivalent to a local proxy. Speaking of caching, we will think of some of the caching technologies we commonly use to cache our static resources, but the old method does not support debugging and is not very flexible. Using Service Worker for caching, we can use javascript code to intercept the browser's http request, set the cached file, return it 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 application less dependent on the network. For example, we have developed a news reading web application. When you open it with a mobile browser and there is a network, you can obtain news content normally. However, if your phone goes into airplane mode, you won’t be able to use this app.

If we use Service Worker for caching, the browser http request will first go through Service Worker and be matched through url mapping. If it is matched, the cached data will be used. If the match fails, it will continue to execute what you specified. action. Normally, if the match fails, the page will display "The web page cannot be opened."

service work life cycle

HTML5 offline storage and cookie storage analysis


##service work demo

<!DOCTYPE html><html lang="en">
  <head>
    <meta charset="utf-8">
    <script>
        navigator.serviceWorker.register("/service-worker.js").then(function(serviceWorker) {            console.log("success!");
        });    </script>
  </head>
  <body>
  </body></html>
This js will be called when the service-worker is successfully registered on the page

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&#39;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&#39;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 an event listening mechanism. The above code monitors the install and fetch events. When the server worker is successfully installed, Call this method, then cache the resource file of the page, fetch the page request event, and the server worker intercepts the user request. When it finds that the requested file hits the cache, it obtains the file from the cache and returns it to the page without going through the server, thereby achieving the purpose of going offline. .

Of course, the functions of service worker are far more than what they are now

indexedDB

indexedDB is a nosql database used to store data locally. It has extremely fast data query speed and can Save the js object directly. It is more efficient than web sql (sqlite), including indexing, transaction processing and robust query functions. indexedDB features:

1. A website may have one or more IndexedDB databases, and each database must have a unique name.

2. A database can contain one or more object stores

一个对象存储(由一个名称惟一标识)是一个记录集合。每个记录有一个键 和一个值。该值是一个对象,可拥有一个或多个属性。键可能基于某个键生成器,从一个键路径衍生出来,或者是显式设置。一个键生成器自动生成惟一的连续正整数。键路径定义了键值的路径。它可以是单个 JavaScript 标识符或多个由句点分隔的标识符。

基本使用方式如下:

var openRequest = indexedDB.open("auto_people", 3);var db; //数据库对象openRequest.onupgradeneeded = function(e)
{    console.log("Running onupgradeeded...");	var thisDB = e.target.result;	if(!thisDB.objectStoreNames.contains("people")){
thisDB.createObjectStore("people", {autoIncrement:true}); //新建一个store并设置主键自增长
}
}//创建成功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);
}//这应该站在别的地方处理,这是做一个代码展示var transaction = db.transaction([&#39;people&#39;], "readwrite"); 
//创建一个连接var store = transaction.objectStore("people");  //获取storevar request = store.add({
   name: &#39;myron&#39;,
   email: &#39;test@qq.com&#39;,
   created: new Date()
}); //添加信息request.onerror = function(e){
   alert(&#39;error!&#39;);    console.dir(e);
} //当添加失败时调用request.onsuccess = function(e){    console.log(&#39;Did it!&#39;);
} //添加成功时调用request = store.get(1);  //获取第一条数据request.onsuccess = function(e)
{    var result = e.target.result;    console.dir(result);    if(result){        //拿到存储的对象
}
}

以上内容就是cookie和HTML5离线存储的分析,大家都了解了吗?

相关推荐:

如何区别html5离线存储和本地缓存实例详解

HTML5离线存储原理

html5的离线存储问题汇总

The above is the detailed content of HTML5 offline storage and cookie storage analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

H5 vs. HTML5: Clarifying the Terminology and RelationshipH5 vs. HTML5: Clarifying the Terminology and RelationshipMay 05, 2025 am 12:02 AM

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

HTML5 Features: The Core of H5HTML5 Features: The Core of H5May 04, 2025 am 12:05 AM

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

H5: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.