Home > Web Front-end > H5 Tutorial > Detailed explanation of html5 offline storage knowledge

Detailed explanation of html5 offline storage knowledge

小云云
Release: 2017-12-05 16:22:16
Original
3399 people have browsed it

STORAGE (storage)

Cookie

Before HTML5 we would use cookies to cache some data on the browser side, such as: logged in user information, historical searches Information and so on. 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 minutes
Cookies.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');
Copy after login

By It can be seen that using cookie storage has the following disadvantages:

The amount of stored data is relatively small

There is no convenient API to operate it

The cookie information will be requested in http When added to the request header, it 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');
Copy after login

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 data cached by sessionStorage will be automatically is cleared, and localStorage will be permanently saved locally as long as it is not cleared manually.

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

Detailed explanation of html5 offline storage knowledge

##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. In the past, it could not be done directly processing tasks. 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

Detailed explanation of html5 offline storage knowledge

#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>
Copy after login

Register on the page This js will be called when the service-worker is successful

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");
        });
    );
};
Copy after login

service worker uses an event listening mechanism. The above code listens to the install and fetch events. When the server worker is successfully installed, this method is called. , then cache the resource file of the page, fetch the page request event, and the server worker intercepts the user request. When it is found 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 function of service worker is far more than what it is now

indexedDB ##indexedDB is a nosql database used to store data locally, with extremely fast Data query speed, and js objects can be saved 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

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. Keys may be based on a key generator, derived from a key path, or set explicitly. A key generator that automatically generates unique consecutive positive integers. The key path defines the path to 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; //数据库对象
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(['people'], "readwrite"); //创建一个连接
var store = transaction.objectStore("people");  //获取store
var request = store.add({
    name: 'myron',
    email: 'test@qq.com',
    created: new Date()
}); //添加信息

request.onerror = function(e){
    alert('error!');
    console.dir(e);
} //当添加失败时调用

request.onsuccess = function(e){
    console.log('Did it!');
} //添加成功时调用

request = store.get(1);  //获取第一条数据

request.onsuccess = function(e){
    var result = e.target.result;
    console.dir(result);
    if(result){
        //拿到存储的对象
	}
}
Copy after login

application cache

The above content is a detailed explanation of HTML5 offline storage knowledge. I hope it can help everyone.

Related recommendations:

Detailed explanation of how to distinguish html5 offline storage and local cache instances

HTML5 offline storage principle and implementation code examples

HTML5 offline storage principle

The above is the detailed content of Detailed explanation of html5 offline storage knowledge. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template