蜗牛789
主机测评与优惠

无插件实现WordPress前端代码压缩且加速页面加载

蜗牛789 2020-01-01 阅读(4786)

随着我们采用的WordPress程序建站推进,会越来越觉得网站的打开速度变慢,这个与我们实际选择的主机是有关系的,但是也与我们网站使用的主题、插件、网站中的图片,以及是否优化WordPress网站性能速度有关系。对于代码前端,我们可以使用压缩插件将代码都压缩起来,这样减少页面的体积。

对于插件有很多,我们可以选择使用WP HTML Compression插件,同时,我们也可以使用下面蜗牛找到的无插件版本效果也是一样的。

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\');

将代码添加到当前主题的Functions.php页面中,我们就可以刷新缓存看看效果。

未经允许不得转载

相关推荐

互动交流中心
蜗牛粉丝QQ交流一群:1074630828
蜗牛粉丝QQ交流二群:859816272
广告赞助联系 QQ :3576243
软文投稿QQ群 :1074630828

站长邮箱:3576243@qq.com
热门文章