离线缓存 manifest

时间:2023-03-09 14:40:26
离线缓存  manifest

程序的离线缓存由一个叫做manifest的文本文件控制,把需要离线缓存的文件列在里面即可,这个列表还可以控制需要缓存的情况,甚至当用户从缓存地址进入到没有缓存的地址应该显示什么

当浏览器下载解析了manifest文件之后,就会换取这些资源并且保存起来无网络使用 ,格式如下:
CACHE MANIFEST     //告诉浏览器这是一个manifest文件

# This is a comment

CACHE:             //每一个部分标题使用大写,这里列出需要缓存的资源
/css/screen.css
/css/offline.css
/js/screen.js
/img/logo.png http://example.com/css/styles.css FALLBACK: //这里定义当一个没有网络的用户尝试跳转到没有缓存的地方时该显示什么
/one
.html /offline.html

NETWORK: //这里定义哪些资源只有连接网络时才可用
register.php
login.php
 
cache   是默认的,如果没有写标题的话,浏览器默认列表里的内容是需要缓存的资源,不能使用通配符(如/images/*)。另外当用户从一个没有声明需要缓存的页面进入另一个被缓存的页面,那么刚才进来的页面也会被恰当地缓存,因此可以利用这个特点,不需要把所有页面都列进去
fallback   每行包含两个值,使用空格隔开,当离线用户尝试访问第一个链接时,应该呈现第二个已经缓存了的页面。举例:
/ /offline.html       表示当离线用户访问所有没有缓存的页面都会转向offline,因为/匹配了所有页面
/images/avatars/ /offline_avatar.png    当离线用户访问/images/avatars/图片目录,会替换为offline_avatar.png
network  如果使用*号,表示除了cache里面的资源,其他都要求网络连接

<!DOCTYPE html>
<html lang="en" manifest="/offline.appcache"> //浏览器只会缓存带有manifest属性的页面
 // your html document
</html>
该文件同时需要使用 text/cache-manifest,在服务器提供相应的支持

一旦缓存成功下载,除非用户清除缓存或者更新manifest文件才会更新缓存,只是更新了服务器上的内容不会更新缓存的,如果只是更新了内容例如CSS文件,那么应该修改版本号触发更新。
CACHE MANIFEST
# Version 9
CACHE:
/css/screen.css
 
Browser bug: Firefox caches the manifest file itself and will not update it even if the manifest has changed on the server. With some server config wizardry, you can tell browsers that the cache of the manifest file is instantly invalidated and should be requested from the server every time it’s referenced. Add this to your .htaccess to put Firefox in its place:

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/cache-manifest "access plus 0 seconds"
</IfModule>
http://html5doctor.com/go-offline-with-application-cache/