在以往的Emlog優化教程中,相信都是使用的代碼壓縮插件,今天主要是分享插件的代碼版本,也就是不使用插件,直接將代碼丟在module.php中就可以,好吧,又消滅一個插件!
以下代碼是扔在module.php里面的
function em_compress_html_main($buffer){ $initial=strlen($buffer); $buffer=explode("<!--em-compress-html-->", $buffer); $count=count ($buffer); for ($i = 0; $i <= $count; $i++){ if (stristr($buffer[$i], '<!--em-compress-html no compression-->')){ $buffer[$i]=(str_replace("<!--em-compress-html no compression-->", " ", $buffer[$i])); }else{ $buffer[$i]=(str_replace("\t", " ", $buffer[$i])); $buffer[$i]=(str_replace("\n\n", "\n", $buffer[$i])); $buffer[$i]=(str_replace("\n", "", $buffer[$i])); $buffer[$i]=(str_replace("\r", "", $buffer[$i])); while (stristr($buffer[$i], ' ')) { $buffer[$i]=(str_replace(" ", " ", $buffer[$i])); } } $buffer_out.=$buffer[$i]; } $final=strlen($buffer_out); $savings=($initial-$final)/$initial*100; $savings=round($savings, 2); $buffer_out.="\n<!--壓縮前的大小: $initial bytes; 壓縮后的大小: $final bytes; 節約:$savings% -->"; return $buffer_out; }
以下代碼是扔在footer.php最末尾(即</html>結尾處)
<?php if(_g('compress_html')=='open'){ $html=ob_get_contents(); ob_get_clean(); echo em_compress_html_main($html); } ?>
以上的代碼有一個模板設置判斷語句,其代碼為以下:
'compress_html' => array( 'type' => 'radio', 'name' => '網站源碼壓縮', 'description' => '', 'values' => array('open' => '壓縮','close' => '關閉'), 'default' => 'open' ),
效果圖:
想要內容里面的pre不被壓縮可使用以下函數:
function unCompress($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; } unCompress($log_content);
轉載請注明出處 AE博客|墨淵 ? EMLOG無插件實現網站源碼壓縮
發表評論