浏览器本身的缓存机制
- 浏览器会对静态文件(html csss js 图片等)进行自动缓存
- 下一次访问该网页,会读取缓存
- 读取缓存之前进行判断, 第一判断缓存时间和服务器上文件的最后一次修改时间
- 如果缓存时间大于最后一次修改时间, 证明缓存之后,服务器上没有对文件进行修改,此时,浏览器会直接读取缓存的文件
- 如果缓存时间小于最后一次修改时间,证明缓存后服务器又对文件进行了修改,此时,浏览器会重新下载服务器上的静态文件,并重新进行缓存。
应用缓存的优点(Application Cache)
使用过程
- 定义manifest文件, 名字自定义 后缀自定义, 建议后缀
appcache
- 在html中使用属性
manifest
引入 manifest文件
应用程序的原理
- 浏览器请求,判断有无appcacheCache
- 如果没有, 从服务器下载相关文件, 并进行缓存
- 如果有, 把缓存文件 加载到浏览器, 并且请求manifest文件,看文件是否更新, 如果manifest文件更新,会从新下载缓存文件,并·更新本地的缓存
manifest文件
CACHE MANIFEST
#version: 0.0.1
CACHE:
缓存文件.html
缓存文件.css
NETWORK:
不缓存的文件.html
FALLBACK:
404.html
applicationCache对象
- 属性
- status 返回缓存的状态
- 方法
- update() 发起应用缓存下载进程
- abort() 取消正在进行的缓存下载
- swapcache() 切换成本地最新的缓存环境
事件
- checking 用户代理检测更新或者在第一次尝试下载manifest文件的时候,本事件往往是第一个触发的
- noupdate 检测出manifest文件没有更新
- downloading 用户代理发现更新并且正在取资源,或者第一次下载manifest文件列表中列举的资源
- progress 用户代理正在下载资源manifest文件中的需要缓存的资源
- updateready manifest中列举的文件已经重新下载并更新成功,接下来js可以使用swapCache()方法更新到应用程序中
error
absolete manifest的请求出现404或者410错误,应用程序缓存被取消
index.html
<!DOCTYPE html>
<html lang="en" manifest="website.appcache">
<head>
<meta charset="UTF-8">
<title>我的网站</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>你的网站很好</h1>
<button onclick="update()">更新</button>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam consequatur illum omnis corrupti minima reprehenderit, illo reiciendis velit officiis voluptates officia aliquam optio obcaecati nam hic provident quae eveniet. Ab.
</p>
<hr>
<a href="01.html">01.html</a> <br>
<hr>
<div id="box"></div>
<div id="status"></div>
<script src="script.js"></script>
<script>
var status_box = document.querySelector("#status");
applicationCache.addEventListener("updateready", function(){
status_box.innerHTML = "缓存已经更新,请稍后...";
setTimeout(function(){
location.reload();
}, 1000)
})
function update(){
applicationCache.update();
}
</script>
</body>
</html>
website.appcache
CACHE MANIFEST
#version 0.1.0
CACHE:
index.html
script.js
style.css
FALLBACK:
offline.html
网友评论