利用minify提高前端性能

2016-10-21 Frank PHP

用程序自动判断要合并文件是否更新来决定是否重新合并,当然也可以合并好了再部署到生产环境。待合并的源文件及目标文件应该在同一个目录,以避免找不到相应的图片资源。

php-minify github

安装

#安装
composer require matthiasmullie/minify
#如果php没有加环境变量, composer没有全局需要下面这样安装:
/usr/local/php/bin/php composer.phar require matthiasmullie/minify

为了能用composer的类库需要修改include/lib/function.base.php 文件中_autoload为spl_autoload_register

合并

require_once EMLOG_ROOT."/vendor/autoload.php" ;
//require_once EMLOG_ROOT.'/vendor/matthiasmullie/minify/src/Minify.php';
//require_once EMLOG_ROOT.'/vendor/matthiasmullie/minify/src/CSS.php';

use MatthiasMullie\Minify;

$minifiedCssPath = EMLOG_ROOT."/content/templates/default/css/blog.min.css" ;
$minifiedJsPath = EMLOG_ROOT."/content/plugins/frank_markdown/lib/minify.js" ;

$css_arr = [
    "css_main" => EMLOG_ROOT."/content/templates/default/main.css" ,
    "css_bootstrap" => EMLOG_ROOT."/admin/views/css/bootstrap.min.css" ,
    "css_prettify" => EMLOG_ROOT."/admin/editor/plugins/code/prettify.css" ,
    "css_editormd" => EMLOG_ROOT."/content/plugins/frank_markdown/css/editormd.css" ,
    "css_gh_fork_ribbon" => EMLOG_ROOT."/content/templates/default/css/gh-fork-ribbon.min.css" ,
] ;
$js_editor_arr = [
    "marked" => EMLOG_ROOT."/content/plugins/frank_markdown/lib/marked.min.js",
    "prettify" => EMLOG_ROOT."/content/plugins/frank_markdown/lib/prettify.min.js",
    "raphael" => EMLOG_ROOT."/content/plugins/frank_markdown/lib/raphael.min.js",
    "underscore" => EMLOG_ROOT."/content/plugins/frank_markdown/lib/underscore.min.js",
    "sequence" => EMLOG_ROOT."/content/plugins/frank_markdown/lib/sequence-diagram.min.js",
    "flowchart-min" => EMLOG_ROOT."/content/plugins/frank_markdown/lib/flowchart.min.js",
    "jquery-flowchart" => EMLOG_ROOT."/content/plugins/frank_markdown/lib/jquery.flowchart.min.js",
    "editormd" => EMLOG_ROOT."/content/plugins/frank_markdown/editormd.js",
] ;
//TODO:读取文件日期,并生成唯一值保存成文件缓存,每次生成的值跟缓存数据做对比,如果不相同则重新合并文件
//以上方案缺点需要缓存支持。直接对比文件时间
$css_minify_time = filemtime($minifiedCssPath) ;
$js_minify_time = filemtime($minifiedJsPath) ;
$css_need_minify = false ;
$js_need_minify = false ;
foreach ($css_arr as $key => $css) {
    $t = filemtime($css) ;
    if($t>$css_minify_time){
        $css_need_minify = true ;
    }
}
foreach ($js_editor_arr as $key => $js) {
    $t = filemtime($js) ;
    if($t>$js_minify_time){
        $css_need_minify = true ;
    }
}
if($css_need_minify){
    $minifier = new Minify\JS();
    foreach ($css_arr as $key => $css) {
        $minifier->add($css);
    }
    $minifier->minify($minifiedCssPath);
}
if($js_need_minify){
    $minifier = new Minify\JS();
    foreach ($js_editor_arr as $key => $js) {
        $minifier->add($js);
    }
    $minifier->minify($minifiedJsPath);
}
<link rel="stylesheet" href="<?php echo TEMPLATE_URL; ?>css/blog.min.css" />

发表评论 登录

Top