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

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

作者: hux1ao | 来源:发表于2018-02-06 11:29 被阅读0次

接上回

  • 上回我们已经完成了应用的所有功能,接下来我们要做的是借助applicationCache使应用可以离线使用
  • 搭建简易nodejs服务器,测试我们的项目
创建应用缓存清单文件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关闭服务器,应用依然能够正常使用!!!

大功告成

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/caxgzxtx.html