HTML5离线缓存

参考文档:http://www.w3cschool.cc/html/html5-app-cache.html

HTML5 应用程序缓存 又称离线缓存 ,即使断线了,刷新后也还是缓存了原来的页面,不会404了

首先,请在文档的<html> 标签中包含 manifest 属性:

<!DOCTYPE HTML>
<html manifest="page.appcache"> <!--这里的page.appcache是一个文件,自己手动生成-->
...
</html>

在Apache,或者在.htaccess文件上加上

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond $1 !^(index\.php|robots\.txt|views|plugins|backup|upload|image|runtime|install)
    RewriteRule ^(.*)$ index.php/$1 [L]
#加上这一句
AddType text/cache-manifest manifest   
 </IfModule>

下面就是生成.appcache文件了。格式是

CACHE MANIFEST
# 2012-02-21 v1.0.0
/theme.css
/logo.gif
/main.js

NETWORK:
login.php

FALLBACK:
/html/ /offline.html

但是一个项目中不会只有这么点文件,要把更多的资源文件。css.js.img等加载进来,所以还需要一个遍历目录的方法。以下是我自己改写的一个方法。

<?php

/**
 * 获取路径下所有文件
 * @param string $folder 路径
 * @param int $levels   处理路径层级
 * @return array  
 * @author lixianghui
 */
function list_files($folder = '', $levels = 100) {
    if (empty($folder) || !$levels) {
        return false;
    }
    $files = array();
    //打开目录
    if ($dir = @opendir($folder)) {
        //读取目录句柄
        while (($file = readdir($dir) ) !== false) {
            //过滤非法字符
            if (in_array($file, array('.', '..')))
                continue;
            //过滤中文
            if (preg_match("/[\x7f-\xff]/", $file))
                continue;
            //判断是否目录
            if (is_dir($folder . '/' . $file)) {
                //递归上一层级
                $files2 = list_files($folder . '/' . $file, $levels - 1);
                //生成目录或合并结果集
                if ($files2)
                    $files = array_merge($files, $files2);
                else
                    $files[] = $folder . '/' . $file . '/';
            } else {
                //文件
                //过滤非资源文件
                if (in_array(pathinfo($file)['extension'], array('css', 'js', 'png', 'jpg', 'gif'))) {
                    $files[] = $folder . '/' . $file;
                }
            }
        }
    }
    @closedir($dir);
    return $files;
}

/**
 * 离线缓存
 * @return void 
 * @author lixianghui
 */
function offline_cache(){
    $list = array();
    $file_str = "";
   //获取目录下的资源文件 $dir_upload = list_files('upload'); $dir_default = list_files('views/default'); $file_array=array_merge($dir_upload,$dir_default); foreach ($file_array as $val) { $file_str.=$val . "\n"; }   //生成appcache文件 $cache_str = "CACHE MANIFEST\n"; $cache_str.="#" . date("Y-m-d H:i:s") . "\n"; $cache_str.=$file_str; $cache_str.="NETWORK:\n\n\n"; $cache_str.="FALLBACK:\nnomore.html"; file_put_contents("page.appcache", $cache_str); }

好了,接下来打开console测试,访问页面会看到缓存的资源都加载成功。如果出现保存请检查资源是否保存,或者是否存在

posted @ 2015-02-02 20:39  Lion_coder  阅读(387)  评论(1编辑  收藏  举报