H5离线缓存--manifest

1,233 阅读3分钟

1、服务器端需要维护一个manifest清单

manifest 文件需要配置正确的 MIME-type,即 "text/cache-manifest"。必须在 web 服务器上进行配置,不同的服务器不一样。
a、 让Apache支持manifest:
新建或编辑现有的 .htaccess文件,在里面加上一行

    AddType text/cache-manifest .manifest

b、让nginx支持manifest文件:
修改mime.types文件,在里面增加manifest文件的映射

 text/cache-manifest manifest

如果服务器没设置,浏览器会报如下的错误:

 Application Cache Error event: Manifest fetch failed (404)

2、新建一个 .manifest文件(推荐使用)

文件里面写上需要处理的文件的列表:

CACHE MANIFEST
# v1.0.0.0 版本号(#表示注释,非必写)
# 需要缓存的文件
https://hahahahah.jpg

# 不需要缓存的页面
NETWORK:
*

# 无法访问页面
FALLBACK
404.html

3、在html标签上添加manifest属性

<html manifest="/cache/abc.manifest">
.....
</html>

4、通过Header设置缓存的各种属性

改变meta标签里面的键值对

<meta http-equiv="Cache-Control" content="max-age=3600" />
<!-- 表示当访问此网页后的一小时内再次访问不会去服务器 -->
<!-- <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> -->
<!-- <meta http-equiv="Pragma" content="no-cache" /> -->
<!-- <meta http-equiv="Expires" content="0" /> -->
<!-- no-cache指示请求或响应消息不能缓存 -->
<!-- no-store用于防止重要的信息被无意的发布。在请求消息中发送将使得请求和响应消息都不使用缓存。 -->
<!-- max-age指示客户机可以接收生存期不大于指定时间(以秒为单位)的响应 -->
<!-- min-fresh指示客户机可以接收响应时间小于当前时间加上指定时间的响应 -->
<!-- max-stale指示客户机可以接收超出超时期间的响应消息。如果指定max-stale消息的值,那么客户机可以接收超出超时期指定值之内的响应消息。 -->

第一次渲染的时候可以在控制台里面看到:

//通过清单下载需要的缓存文件
Creating Application Cache with manifest https://hahahahah/cache/abc.manifest
//下载并执行相应的事件
abc.html?product_id=329:1 Application Cache Checking event
abc.html?product_id=329:1 Application Cache Downloading event
abc.html?product_id=329:1 Application Cache Progress event (0 of 1) https://hahahahah.jpg
abc.html?product_id=329:1 Application Cache Progress event (1 of 1) 
abc.html?product_id=329:1 Application Cache Cached event

再次刷新:

//  文件从缓存中获取文件
Document was loaded from Application Cache with manifest https://hahahahah/cache/abc.manifest
abc.html?product_id=329:1 Application Cache Checking event
abc.html?product_id=329:1 Application Cache NoUpdate event

可以再application里面查看application Cache 里面的列表。里面显示着我们缓存下来的文件。

5、更新缓存

a. 修改manifest文件
b. 通过js清除缓存,window.applicationCache.update();
c. 清除浏览器缓存

6、如何不通过服务器配置清单,在本地进行设置实现缓存效果(不建议线上项目中使用)

  <!--直接在meta标签里面设置manifest文件类型,建议放在前面-->
  <!--这种情况是在本地服务跑,不需要去配置服务器的清单-->
  <meta http-equiv="content-type" content="text/cache-manifest" />