实现步骤
代码压缩之后也会提高用户访问速度,进而更利于seo的优化
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.这样就基本实现主题的代码压缩了,但是这样的话,我们平常文章内容中分享的代码也会随着被压缩,接下来我们需要把文章中的pre标签排除一下。接着在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);
?>
4.将文章展示页面echo_log.php、page.php文件中的 $log_content 给套一下
slbys($log_content)
温馨提示
压缩源码意味着删除换行,空格等无效字符,所以这个时候就会出现一些问题,比如js的//注释把所有js代码都注释掉了,还有js设置变量,函数没有加分号等不正规的编写都会导致js无法正常运行,所以把//注释换成/**/,把该加的;分号毫不吝啬的加上。再去看控制台是否报错。
压缩效果
在次查看页面源码就会注意到明显的差别了
转载阿奇下载
未经允许不得转载:
作者: 路羽, 转载或复制请以 超链接形式 并注明出处 路羽博客。
原文地址: 《Emlog-实现全主题代码压缩方法》 发布于2022-2-11
支持一下,路羽博客有你更精彩