Implementation of HTML5 offline application and client storage

不言
Release: 2018-05-05 11:25:20
Original
1357 people have browsed it

This article mainly introduces the relevant information about the implementation of HTML5 offline application and client storage. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to 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 {
    // 执行离线状态时的任务
}
Copy after login

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 Two events online and offline are defined.

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() {
    // 执行离线状态时的任务
});
Copy after login

In actual applications, It is best to obtain the initial state through navigator.onLine after the page is loaded. 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
Copy after login

Then quoted in html:

<html manifest="./xxx.manifest">
Copy after login

xxx. The MIME type of the manifest 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 starting to download application cache resources

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

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

  • cached: Triggered when the application cache is 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, usually called cookie directly, is used by the client The end is used to store session information. The standard requires servers to send the Set-Cookie HTTP header as part of the response to any HTTP request, which contains session information. Server response header example:

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

Then the browser Set-Cookie's session information, and then adds the Cookie HTTP header to each request to send the information back to the server, as follows:

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

The additional information sent back to the server can be used to uniquely authenticate the client from which it was sent Which request.

The complete cookie includes:

  1. Name: A name that uniquely identifies the cookie. Must be URL encoded.

  2. Value: The string value stored in the cookie. Must be URL encoded.

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

基本用法

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

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

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

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

// cookie 的名称不存在
document.cookie = &#39;name4=value4&#39;
// name1=value1;name2=value2;name3=value3;name4=value4;
// 而不是 name4=value4;
// cookie 的名称存在
document.cookie = &#39;name3=value4&#39;
// name1=value1;name2=value2;name3=value4;
Copy after login

从上面的代码我们可以看出,我们要读取或者修改或者删除指定 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);
    }
};
Copy after login

使用方法:

// 设置 cookie
CookieUtil.set(&#39;name&#39;, &#39;lai&#39;);
CookieUtil.set(&#39;sex&#39;, &#39;man&#39;);

// 读取 cookie
CookieUtil.get(&#39;name&#39;); // &#39;lai&#39;
CookieUtil.get(&#39;sex&#39;); // &#39;man&#39;

// 删除 cookie
CookieUtil.unset(&#39;name&#39;);
CookieUtil.unset(&#39;sex&#39;);

// 设置 cookie,包括它的路径、域、失效日期
CookieUtil.set(&#39;name&#39;, &#39;lai&#39;, &#39;/&#39;, &#39;www.laixiangran.cn&#39;, new Date());
Copy after login

大小限制

  • 每个域的 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);
        };
    }
}
Copy after login

限制

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

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

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


The above is the detailed content of Implementation of HTML5 offline application and client storage. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!