offline web applications

本文介绍如何创建离线可用的Web应用程序,包括使用localStorage存储用户数据、通过manifest文件定义缓存资源及监听在线离线事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

offline web applications


The network is a key component of any web application, whether it is used to download JavaScript, CSS, and HTML source files and accompanying resources (images, videos, …) or to reach web services (XMLHttpRequest and<forms>).

Yet having offline support for web applications can be very useful to users. Imagine, for example, a webmail application that allows users to read emails already in their inbox and write new messages even when they are not connected.

The mechanism used to support offline web applications can also be used to improve an application’s performance by storing data in the cache or to make data persistent between user sessions and when reloading and restoring pages.

Demo: a To Do List Manager

To see an offline web application in action, watch Vivien Nicolas’ demo, which shows a to do list manager working online and offline on an N900 running Firefox:

You can also check out the live demo of the application.

Creating your Own Offline Application

For a web application to work offline, you need to consider three things:

Let’s see how to use each of these components.

Storage: Persistent Data

DOM storage lets you store data between browser sessions, share data between tabs and prevent data loss (for example from page reloads or browser restarts). The data are stored as strings (for example a JSONified JavaScript object) in a Storage object.

There are two kinds of storage global objects: sessionStorage andlocalStorage.

  • sessionStorage maintains a storage area that’s available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window causes a new session to be initiated.
  • localStorage maintains a storage area that can be used to hold data over a long period of time (e.g. over multiple pages and browser sessions). It’s not destroyed when the user closes the browser or switches off the computer.

Both localStorage and sessionStorage use the following API:

window.localStorage and window.sessionStorage {
  long length; // Number of items stored
  string key(long index); // Name of the key at index
  string getItem(string key); // Get value of the key
  void setItem(string key, string data); // Add a new key with value data
  void removeItem(string key); // Remove the item key
  void clear(); // Clear the storage
};

Here is an example showing how to store and how to read a string:

// save the string
function saveStatusLocally(txt) {
  window.localStorage.setItem("status", txt);
}
 
// read the string
function readStatus() {
   return window.localStorage.getItem("status");
}

Note that the storage properties are limited to an HTML5 origin (scheme + hostname + non-standard port). This means that window.localStorage from http://foo.com is a different instance of window.localStorage from http://bar.com. For example, http://google.com can’t access the storage of http://yahoo.com.

Are We Offline?

Before storing data, you may want to know if the user is online or not. This can be useful, for example, to decide whether to store a value locally (client side) or to send it to the server.

Check if the user is online with the navigator.onLine property.
In addition, you can be notified of any connectivity changes by listening to theonline and offline events of the window element.

Here is a very simple piece of JavaScript code, which sends your status to a server (à la twitter).

  • If you set your status and you’re online, it sends the status.
  • If you set your status and you’re offline, it stores your status.
  • If you go online and have a stored status, it sends the stored status.
  • If you load the page, are online, and have a stored status, it sends the stored status.
function whatIsYourCurrentStatus() {
  var status = window.prompt("What is your current status?");
  if (!status) return;
  if (navigator.onLine) {
    sendToServer(status);
  } else {
    saveStatusLocally(status);
  }
}
 
function sendLocalStatus() {
  var status = readStatus();
  if (status) {
    sendToServer(status);
    window.localStorage.removeItem("status");
  }
}
 
 
window.addEventListener("load", function() {
   if (navigator.onLine) {
     sendLocalStatus();
   }
}, true);
 
window.addEventListener("online", function() {
  sendLocalStatus();
}, true);
 
window.addEventListener("offline", function() {
  alert("You're now offline. If you update your status, it will be sent when you go back online");
}, true);

Offline Resources: the Cache Manifest

When offline, a user’s browser can’t reach the server to get any files that might be needed. You can’t always count on the browser’s cache to include the needed resources because the user may have cleared the cache, for example. This is why you need to define explicitly which files must be stored so that all needed files and resources are available when the user goes offline: HTML, CSS, JavaScript files, and other resources like images and video.

The manifest file is specified in the HTML and contains the explicit list of files that should be cached for offline use by the application.

<html manifest="offline.manifest">

Here is an example of the contents of a manifest file:

CACHE MANIFEST
fonts/MarketingScript.ttf
css/main.css
css/fonts.css
img/face.gif
js/main.js
index.xhtml

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

See the documentation for more details on the manifest file format and cache behavior.

Summary

The key components you should remember to think about when making your application work offline are to store the user inputs in localStorage, create acache manifest file, and monitor connection changes.

Visit the Mozilla Developer Center for the complete documentation.

原文链接:http://hacks.mozilla.org/2010/01/offline-web-applications/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值