应用缓存
- 应用缓存 是html5 的一项技术,可以缓存服务器发送过来的文件有以下几个优点:
- 离线浏览
- 提升页面加载速度
- 可以缓解服务器的压力
- 应用缓存的实现通过创建一个manifest文件来指定缓存的文件
话不多说,首先建立一个服务器
- 使用 koa 创建一个http服务器
const koa = require("koa")
const Router = require("koa-router")
const static = require("koa-static")
const fs = require("fs")
const server = new koa()
server.use(static(__dirname))
const router = new Router()
server.use(router.routes()).use(router.allowedMethods())
router.get("/hello",async ctx=>{
const data = fs.readFileSync("./Hello.html","utf8")
ctx.body = data
})
router.get("/index",async ctx=>{
const data = fs.readFileSync("./index.html","utf8")
ctx.body = data
})
server.listen(8888)
静态文件
- index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>application cache</title>
<link rel="stylesheet" href="./index.css">
<link rel="stylesheet" href="./style1.css">
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h1>Application Cache</h1>
<h2>这是一个测试文件</h2>
</body>
</html>
- Hello.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
- index.css
*{
margin: 0;
padding: 0;
list-style-type: none;
text-decoration: none;
}
h1{
font-weight: 400;
color: hotpink;
text-align: center;
}
- style.css
*{
margin: 0;
padding: 0;
list-style-type: none;
text-decoration: none;
}
h2{
font-weight: 400;
color: lightgreen;
text-align: center;
}
- style1.css
*{
margin: 0;
padding: 0;
list-style-type: none;
text-decoration: none;
}
h2{
font-weight: 400;
color: lightsalmon;
text-align: center;
}
打开浏览器看看效果
- 说明服务器已经建好了
进行应用缓存
- 在 html 标签里添加 manifest=“demo.appcache” 文件
<!DOCTYPE html>
<html manifest="demo.appcache">
<head>
<meta charset="utf-8">
<title>application cache</title>
<link rel="stylesheet" href="./index.css">
<link rel="stylesheet" href="./style1.css">
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h1>Application Cache</h1>
<h2>这是一个测试文件</h2>
</body>
</html>
- demo.appcache
CACHE MANIFEST
# CACHE 是需要缓存的文件
CACHE:
index.html
index.css
style1.css
# NETWORK 是不需要缓存的文件
NETWORK:
style.css
FALLBACK:
#当第一个文件加载不出来的时候,就会加载第二个文件
style.css/style1.css
连接网络
离线之后
为什么第二行文字的颜色会改变呢?因为我只缓存了style1.css文件,但是没有缓存style.css文件,因此没有加载到style.css文件的时候,就会去加载style1.css
又连接网络
总结:
- 离线缓存确实可以帮助我们实现文件的缓存,在离线的时候可以不影响用户的体验
- 但是需要第一次对服务器的访问,第一次访问服务器之后,manifest会把需要离线缓存的文件缓存下来,因此可能有时候第一次访问的时候,页面加载会比较慢,但是之后因为有了应用缓存,之后加载页面就会变得很快,这就是应用缓存的好处