EMLOG无插件实现全站代码压缩的方法
相信很多站长都注意过博客插件自带的CSS和JS文件释放出来会让网站源代码变得十分凌乱,因此很多站长开始选择通过源代码压缩的方式整理源代码并提升加载速度,现在就来为大家分享一下EMLOG无插件实现全站代码压缩的方法。
一、操作步骤
1、打开模板文件module.php,在合适的位置添加如下代码
<?php //全站代码压缩 function slys($sheli) { $initial = strlen($sheli); $sheli = explode("<!--slys-->", $sheli); $count = count($sheli); for ($i = 0; $i <= $count; $i++) { if (stristr($sheli[$i], '<!--slys end-->')) { $sheli[$i] = str_replace("<!--slys end-->", " ", $sheli[$i]); } else { $sheli[$i] = str_replace("\t", " ", $sheli[$i]); $sheli[$i] = str_replace("\n\n", "\n", $sheli[$i]); $sheli[$i] = str_replace("\n", "", $sheli[$i]); $sheli[$i] = str_replace("\r", "", $sheli[$i]); while (stristr($sheli[$i], ' ')) { $sheli[$i] = str_replace(" ", " ", $sheli[$i]); } } $sheli_out .= $sheli[$i]; } $final = strlen($sheli_out); $savings = ($initial - $final) / $initial * 100; $savings = round($savings, 2); $sheli_out .= "\n<!--压缩前的大小: {$initial} bytes; 压缩后的大小: {$final} bytes; 节约:{$savings}% -->"; return $sheli_out; }?>
2、打开模板文件footer.php,在末尾添加如下代码
<?php $html=ob_get_contents();ob_get_clean();echo slys($html);?>
3、打开网站首页,通过查看源代码的方式查看效果
二、原理解析
通过PHP代码判断源代码中的空格等,同时对其进行精简,只会影响到源代码而不会影响前台展示效果
三、注意事项
EMLOG无插件实现全站代码压缩教程同时也会直接影响到pre标签,因此如果网站中有添加该标签且想压缩pre中的代码,则需要执行下面的操作
1、打开模板文件module.php,在合适的位置继续添加如下代码
<?php //不压缩pre function slbys($content) { if (preg_match_all('/(crayon-|<\\/pre>)/i', $content, $matches)) { $content = '<!--slys--><!--slys end-->' . $content; $content .= '<!--slys end--><!--slys-->'; } return $content; } slbys($log_content); ?>
2、打开模板文件echo_log.php和page.php,将其中的$log_content替换为slbys($log_content)即可