网页制作 发布日期:2025/10/31 浏览次数:1
支持离线 Web 应用开发是 HTML5 的另一个重点。所谓离线 Web 应用,就是在设备不能上网的情况下仍然可以运行的应用。
开发离线Web 应用需要几个步骤。首先是确保应用知道设备是否能上网,以便下一步执行正确的操作。然后,应用还必须能访问一定的资源(图像、Javascript、CSS等),只有这样才能正常工作。最好,必须有一块本地空间用户保存数据,无论能否上网都不妨碍读写。
HTML5 及其相关的 API让开发离线应用成为现实。
离线检测
要知道设备是否在线还是离线,HTML5 定义了一个 navigator.onLine 属性,这个属性值为 true 表示设备能上网,值为 false 表示设备离线。
if (navigator.onLine) {
    // 正常工作
} else {
    // 执行离线状态时的任务
}
由于 navigator.onLine 存在一定的兼容性问题,因此除了 navigator.onLine 属性之外,为了更好地确定网络是否可用,HTML5 还定义了两个事件 online 和 offline。
当网络在离线和在线之间切换时在 window 对象上触发这两个事件:
window.addEventListener('online', function() {
    // 正常工作
});
window.addEventListener('offline', function() {
    // 执行离线状态时的任务
});
在实际应用中,最好在页面加载后,最好先通过 navigator.onLine 取得初始的状态。然后通过上述两个事件来确定网络连接状态是否变化。当上述事件触发时,navigator.onLine 属性的值也会改变,不过必须要手工轮询这个属性才能检测到网络状态的变化。
应用缓存
HTML5 的应用缓存(application cache),或者简称为 appcache,是专门为开发离线 Web 应用而设计的。Appcache 就是从浏览器的缓存中分出来的一块缓存区。要想在这个缓存中保存数据,可以使用一个描述文件(manifest file),列出要下载和缓存的资源。描述文件示例:
CACHE MANIFEST # Comment file.js file.css
然后在 html 中引用:
<html manifest="./xxx.manifest">
xxx.manifest 文件的 MIME 类型必须是 text/cache-manifest。
该 API 的核心是 applicationCache 对象,这个对象有一个 status 属性,属性的值是常量,表示应用缓存的如下当前状态:
相关事件:
一般来讲,这些事件会随着页面加载按上述顺序依次触发。也可以通过调用 update() 方法手动触发上述事件。
数据存储
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 包括:
复制代码代码如下: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());
大小限制
Web Storage
Web Storage 主要定义了两种对象:sessionStorage 和 localStorage,是 Storage 对象的实例,这两个对象区别如下:
Storage 类型有如下方法:
对 sessionStorage 和 localStorage 进行操作都会触发 storage 事件,该事件对象有以下属性:
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);
        };
    }
}
限制
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。