您当前的位置:易学堂 > EM&TP

Emlog无插件实现全站代码压缩

时间:2019-02-12 17:13:53

将以下代码放在模版的module.php中:

<?php
//全站代码压缩
function maple5($maple){
    $initial=strlen($maple);
    $maple=explode("<!--em-compress-html-->", $maple);
    $count=count ($maple);
    for ($i = 0; $i <= $count; $i++){
        if (stristr($maple[$i], '<!--em-compress-html no compression-->')){
            $maple[$i]=(str_replace("<!--em-compress-html no compression-->", " ", $maple[$i]));
        }else{
            $maple[$i]=(str_replace("\t", " ", $maple[$i]));
            $maple[$i]=(str_replace("\n\n", "\n", $maple[$i]));
            $maple[$i]=(str_replace("\n", "", $maple[$i]));
            $maple[$i]=(str_replace("\r", "", $maple[$i]));
            while (stristr($maple[$i], '  '))
            {
            $maple[$i]=(str_replace("  ", " ", $maple[$i]));
            }
        }
        $maple_out.=$maple[$i];
    }
    $final=strlen($maple_out);
    $savings=($initial-$final)/$initial*100;
    $savings=round($savings, 2);
    $maple_out.="\n<!--压缩前的大小: $initial bytes; 压缩后的大小: $final bytes; 节约:$savings% -->";
    return $maple_out;
}
?>

以下代码放在footer.php最末尾(即后面)

<?php $html=ob_get_contents();ob_get_clean();echo maple5($html);?>

如果要实现不压缩pre中的代码,要在module.php中加入下面代码:

<?php 
//不压缩pre
function maplepre($content){
	if(preg_match_all('/(crayon-|<\/pre>)/i',$content,$matches)){
		$content = '<!--em-compress-html--><!--em-compress-html no compression-->'.$content;
		$content.= '<!--em-compress-html no compression--><!--em-compress-html-->';
	}
	return $content;
}
maplepre($log_content);
?>

然后在echo_log.php、page.php文件中的$log_content用下面代码替换:

maplepre($log_content)