WordPress压缩html代码提升网页加载速度

作者: 时间:
浏览 : 784

对WordPress进行html代码压缩可以实现WordPress加速,此处保哥分享的是免Gzip插件来实现。压缩代码分为两部分,第一部分是压缩html代码,第二部分是解决代码压缩后导致html里的注释挤到一行,使很多代码失效,特别是部分js代码失效。

在当前主题模板下的functions.php中加以下代码:

/**压缩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');
/**自动在存在高亮代码的文章收尾插入免压缩注释**/
function Code_Box($content) {
$matches = array();
/**以下是匹配高亮代码的关键词,本代码适用于 Crayon Syntax Highlighter 插件,其他插件请自行分析关键词即可**/
$c = "/(crayon-|<\/pre>)/i";
if(preg_match_all($c, $content, $matches) && is_single()) {
$content = '<!--wp-compress-html--><!--wp-compress-html no compression-->'.$content;
$content.= '<!--wp-compress-html no compression--><!--wp-compress-html-->';
}
return $content;
}
add_filter( "the_content", "Code_Box" );

 

Tag标签:

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注