纯代码实现WordPress压缩源代码减少体积提速网站页面

WordPress随着运营时间加长,以及数据内容增加会降低打开速度。这个时候我们虽然可以通过升级服务器的配置和用缓存插件提速,但是有必要的可以将前端HTML代码压缩,这样也可以降低体积提速。

虽然我们也可以用到一些插件实现,但是这里其实没有必要,可以用代码实现。

function wp_compress_html(){
function wp_compress_html_main ($buffer){
$initial=strlen($buffer);
$buffer=explode("<!--wp-compress-html-->", $buffer);
$count=count ($buffer);
for ($i = 0; $i <= $count; $i++){
if (stristr($buffer[$i], '<!--wp-compress-html no compression-->')) {
$buffer[$i]=(str_replace("<!--wp-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;}
ob_start("wp_compress_html_main");}
add_action('get_header', 'wp_compress_html');

通过代码可以实现压缩。但是有些JS是不希望被压缩的。

<!--wp-compress-html--><!--wp-compress-html no compression-->
不要被压缩的内容
<!--wp-compress-html no compression--><!--wp-compress-html-->

不要被压缩的内容,我们可以将上面代码放到源代码里。

5/5 - (1 vote)
© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享