实战·基于客户端存储的可离线使用web应用——myTasks(4

2018-02-06  本文已影响0人  hux1ao

接上回

创建应用缓存清单文件task.appcache
CACHE MANIFEST
#Rev 1

CACHE:
index.html
style.css
app.js
image/favicon.ico

NETWORK:

其中 cache表示需要缓存的文件名,network表示需要使用网络访问的文件名
我们在index.html中的html标签中使用该文件

<html lang="en" manifest="tasks.appcache">
自动更新应用

监听updateready事件,在updateready触发时,执行更新

if ('applicationCache' in window) {
      var appCache = window.applicationCache
      appCache.addEventListener('updateready', function () {
        appCache.swapCache()
        if (confirm('应用可以更新,是否现在更新')) {
          window.location.reload()
        }
      }, false)
    }

我们的应用,在第一次加载之后,后边就不需要使用网络访问啦!!!
我们可以在服务器上试一下

但是,服务器呢???

40行代码的简单服务器

// http.js
var PORT = 3000;//

var http = require('http');
var url=require('url');
var fs=require('fs');
var MIME=require('./MIME').types;//
var path=require('path');

var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    var realPath = path.join("./www", pathname);    //这里设置自己的文件名称;
    var ext = path.extname(realPath);
    ext = ext ? ext.slice(1) : 'unknown';
    fs.exists(realPath, function (exists) {
        if (!exists) {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });

            response.write("This request URL " + pathname + " was not found on this server.");
            response.end();
        } else {
            fs.readFile(realPath, "binary", function (err, file) {
                if (err) {
                    response.writeHead(500, {
                        'Content-Type': 'text/plain'
                    });
                    response.end();
                } else {
                    var contentType = MIME[ext] || "text/plain";
                    response.writeHead(200, {
                        'Content-Type': contentType
                    });
                    response.write(file, "binary");
                    response.end();
                }
            });
        }
    });
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");

在终端中输入node http.js在地址栏输入localhost:3000/index.html就可以访问到我们的应用,然后,
control + c关闭服务器,应用依然能够正常使用!!!

大功告成

上一篇 下一篇

猜你喜欢

热点阅读