Home  >  Article  >  Web Front-end  >  Detailed explanation of H5 offline application and client storage usage

Detailed explanation of H5 offline application and client storage usage

php中世界最好的语言
php中世界最好的语言Original
2018-05-07 17:38:412524browse

This time I will bring you a detailed explanation of the use of H5 offline applications and client storage. What are the precautions when using H5 offline applications and client storage? Here are practical cases, let’s take a look.

Supporting offline web application development is another focus of HTML5. The so-called offline web applications are applications that can still run even when the device cannot access the Internet.

Developing offline web applications requires several steps. The first is to make sure the app knows whether the device has Internet access so it can take the correct action next. Then, the application must also have access to certain resources (images, Javascript, CSS, etc.) in order to work properly. Best, there must be a local space for users to save data, and reading and writing will not be hindered regardless of whether they have access to the Internet.

HTML5 and its related APIs make developing offline applications a reality.

Offline detection

To know whether the device is online or offline, HTML5 defines a navigator.onLine attribute. If this attribute value is true, it means the device Can access the Internet. A value of false indicates that the device is offline.

if (navigator.onLine) {
    // 正常工作
} else {
    // 执行离线状态时的任务
}

Due to certain compatibility issues with navigator.onLine, in addition to the navigator.onLine attribute, in order to better determine whether the network is available, HTML5 also defines two events, online and offline.

These two events are triggered on the window object when the network switches between offline and online:

window.addEventListener('online', function() {
    // 正常工作
});
window.addEventListener('offline', function() {
    // 执行离线状态时的任务
});

In practical applications, it is best to pass the navigator first after the page is loaded. .onLine gets the initial state. Then use the above two events to determine whether the network connection status changes. When the above event is triggered, the value of the navigator.onLine property will also change, but this property must be manually polled to detect changes in network status.

Application cache

HTML5’s application cache, or appcache for short, is specifically designed for developing offline web applications. . Appcache is a cache area separated from the browser's cache. To save data in this cache, you can use a manifest file that lists the resources to be downloaded and cached. Description file example:

CACHE MANIFEST
# Comment
file.js
file.css

Then referenced in html:

<html manifest="./xxx.manifest">

xxx.manifest The MIME type of the file must be text/cache-manifest.

The core of this API is the applicationCache object. This object has a status attribute. The value of the attribute is a constant, indicating the following current status of the application cache:

  • 0: None Cache, that is, there is no application cache related to the page

  • 1: Idle, that is, the application cache has not been updated

  • 2: Checking, that is Downloading the description file and checking for updates

  • 3: Downloading, that is, the application cache is downloading the resources specified in the description file

  • 4: Update Completed, that is, the application cache has updated the resources, and all resources have been downloaded and can be used through swapCache()

  • 5: Obsolete, that is, the description file of the application cache is no longer available exists, so the page can no longer access the application cache

Related events:

  • checking: Triggered when the browser looks for updates to the application cache

  • error: Triggered when an error occurs during checking for updates or downloading resources

  • noupdate: Triggered when checking the description file and finding that the file has no changes

  • downloading: Triggered when downloading application cache resources starts

  • progress: Continuously during the process of file download application cache Triggered

  • updateready: Triggered when the new application cache of the page has been downloaded and can be used through swapCache()

  • cached: Triggered in the application cache Triggered when fully available

Generally speaking, these events will be triggered in the above order as the page loads. The above events can also be triggered manually by calling the update() method.

Data Storage

Cookie

HTTP Cookie,通常直接叫做 cookie,是在客户端用于存储会话信息的。该标准要求服务器对任意 HTTP 请求发送 Set-Cookie HTTP 头信息作为响应的一部分,其中包含会话信息。服务器响应头示例:

HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: name=value
Other-header: other-header-value

然后浏览器 Set-Cookie 的会话信息,之后为每个请求添加 Cookie HTTP 头将信息发送回服务器,如下所示:

GET /index.html HTTP/1.1
Cookie: name=value
Other-header: other-header-value

发送回服务器的额外信息可以用于唯一验证客户来自于发送的哪个请求。

完整的 cookie 包括:

  1. 名称: 一个唯一确定 cookie 的名称。必须被 URL 编码。

  2. 值: 存储在 cookie 中的字符串值。必须被 URL 编码。

  3. 域: cookie 对于哪个域是有效的。

  4. 路径: 对于指定域中的那个路径,应该向服务器发送 cookie。

  5. 失效时间: 表示 cookie 何时应该被删除的时间戳

  6. 安全标志: 指定后,cookie 只有在使用 SSL 连接的时候才发送到服务器。

复制代码

代码如下:

Set-Cookie:name=value; domain=www.laixiangran.cn; path=/; expires=Mon, 29 Oct 2018 03:53:10 GMT; secure;

基本用法

在 JavaScript 中操作 cookie 有些复杂,这是因为 document.cookie 属性在不同的使用方式中表现出不同的行为。

当用来获取属性值时,document.cookie 返回当前页面可用的所有 cookie 字符串,一系列由分号隔开的键值对,如下所示:

document.cookie
// name1=value1;name2=value2;name3=value3;

当用来设置值时,document.cookie 属性会设置一个新的 cookie 字符串添加到现有的 cookie 集合中,并不会像普通对象设置属性一样覆盖原 cookie 的值,除非设置的 cookie 的名称已经存在,如下所示:

// cookie 的名称不存在
document.cookie = 'name4=value4'
// name1=value1;name2=value2;name3=value3;name4=value4;
// 而不是 name4=value4;
// cookie 的名称存在
document.cookie = 'name3=value4'
// name1=value1;name2=value2;name3=value4;

从上面的代码我们可以看出,我们要读取或者修改或者删除指定 cookie 的值都不是很直观方便,因此我们可以封装一些方法,方便我们对 cookie 的操作:

var CookieUtil = {
    get: function (name) {
        var cookieName = encodeURIComponent(name) + "=",
            cookieStart = document.cookie.indexOf(cookieName),
            cookieValue = null,
            cookieEnd;
        if (cookieStart > -1) {
            cookieEnd = document.cookie.indexOf(";", cookieStart);
            if (cookieEnd == -1) {
                cookieEnd = document.cookie.length;
            }
            cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
        }
        return cookieValue;
    },
    set: function (name, value, expires, path, domain, secure) {
        var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
        if (expires instanceof Date) {
            cookieText += "; expires=" + expires.toGMTString();
        }
        if (path) {
            cookieText += "; path=" + path;
        }
        if (domain) {
            cookieText += "; domain=" + domain;
        }
        if (secure) {
            cookieText += "; secure";
        }
        document.cookie = cookieText;
    },
    unset: function (name, path, domain, secure) {
        this.set(name, "", new Date(0), path, domain, secure);
    }
};

使用方法:

// 设置 cookie
CookieUtil.set('name', 'lai');
CookieUtil.set('sex', 'man');
// 读取 cookie
CookieUtil.get('name'); // 'lai'
CookieUtil.get('sex'); // 'man'
// 删除 cookie
CookieUtil.unset('name');
CookieUtil.unset('sex');
// 设置 cookie,包括它的路径、域、失效日期
CookieUtil.set('name', 'lai', '/', 'www.laixiangran.cn', new Date());

大小限制

  • 每个域的 cookie 总数是有限,不同浏览器之间所有不同,IE6 以下是最多 20 个,IE7 以上最多 50 个,Firefox最多 50 个,Opera 最多 30 个,Safari 和 Chrome 不限制。

  • cookie 的尺寸也有限制,大多数浏览器有大约 4096B。

Web Storage

  • Web Storage 的目的是克服由 cookie 带来的一些限制,当数据需要被严格控制在客户端上时,无须持续地将数据发回服务器。Web Storage 的两个主要目标是:

  • 提供一种在 cookie 之外存储会话数据的路径。

  • 提供一种存储大量可以跨会话存在的数据的机制。

Web Storage 主要定义了两种对象:sessionStorage 和 localStorage,是 Storage 对象的实例,这两个对象区别如下:

  • sessionStorage: 存储特定于某个会话的数据,也就是该数据只保持到浏览器关闭。存储数据大小大多数限制在 2.5M,少数浏览器限制在 5M 或者不限制。

  • localStorage: 数据保存到通过 JavaScript 删除或者是用户清除浏览器缓存。存储数据大小大多数限制在 5M,少数浏览器限制在 2.5M 或者不限制。

Storage 类型有如下方法:

  • clear(): 删除所有值。

  • getItem(name): 根据指定的名字 name 获取对应的值。

  • key(index): 获取 index 位置处的值的名字。

  • removeItem(name): 删除由 name 指定的键值对。

  • setItem(name, value): 为指定的 name 设置一个对应的值,值为字符串。

对 sessionStorage 和 localStorage 进行操作都会触发 storage 事件,该事件对象有以下属性:

  • domain: 发生变化的存储空间的域名。

  • key: 设置或者删除的键名。

  • newValue: 如果是设置值,则是新值;如果是删除键,则是null。

  • oldValue: 键被更改之前的值。

IndexedDB

Indexed Database API,简称为 IndexedDB,是在浏览器中保存结构化数据的一种数据库。其思想是创建一套 API,方便保存和读取 JavaScript 对象,同时还支持查询和搜索。

IndexedDB 设计的操作完全是异步进行的。因此,大多数操作会以请求方式进行。

基本用法

var indexedDB = window.indexedDB || window.msIndexedDB || window.mozIndexedDB || window.webkitIndexedDB, // 获取 indexedDB
    request,
    store,
    database,
    users = [
        {
            username: "007",
            firstName: "James",
            lastName: "Bond",
            password: "foo"
        },
        {
            username: "ace",
            firstName: "John",
            lastName: "Smith",
            password: "bar"
        }
    ];
// 打开数据库
request = indexedDB.open("example");
// 注册 onerror 及 onsuccess 事件
request.onerror = function (event) {
    alert("Something bad happened while trying to open: " + event.target.errorCode);
};
request.onsuccess = function (event) {
    database = event.target.result;
    
    // 操作数据库
    initializeDatabase();
};
function initializeDatabase() {
    if (database.version != "1.0") {
    
        // 设置数据库版本号
        request = database.setVersion("1.0");
        request.onerror = function (event) {
            alert("Something bad happened while trying to set version: " + event.target.errorCode);
        };
        request.onsuccess = function (event) {
        
            // 使用 users 创建对象存储空间
            store = database.createObjectStore("users", {keyPath: "username"});
            var i = 0,
                len = users.length;
            while (i < len) {
            
                // 插入新值
                store.add(users[i++]);
            }
            alert("Database initialized for first time. Database name: " + database.name + ", Version: " + database.version);
        };
    } else {
        alert("Database already initialized. Database name: " + database.name + ", Version: " + database.version);
        
        // transaction() 创建事务,objectStore() 将存储空间传入事务
        request = database.transaction("users").objectStore("users").get("007");
        request.onsuccess = function (event) {
            alert(event.target.result.firstName);
        };
    }
}

限制

  • 和 Web Storage类似,只能由同源(相同协议、域名和端口)页面操作,因此不能跨域共享信息。

  • Firefox 大小上限为 50M,移动端的 Firefox 大小上限为 5M,不允许本地文件访问。

  • Chrome 大小上限为 5M,允许本地文件访问。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

webpack打包压缩js与css步骤详解

加载移除js与css文件步骤详解

The above is the detailed content of Detailed explanation of H5 offline application and client storage usage. 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