Html代码压缩的好处
Html前端代码压缩后会减少体积大小,从而提高网站的打开速度,这对于wordpress网站的速度优化十分重要,特别当你用的是小水管主机和服务器的时候提升最大,WordPress前端代码压缩还有一个好处就是可以防止别人轻易的扒走你的代码,间接的增加扒手扒代码的人力成本。
代码实现
将以下代码复制到WordPress主题目录下的functions.php文件的最后一个 ?> 之前即可 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//压缩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代码,压缩之后很可能会导致代码失效,这就需要自定义哪些代码不压缩。
解决方法就是为不希望被压缩的代码打上下面的标签即可。
1 2 3 |
<!--wp-compress-html--><!--wp-compress-html no compression--> 此处代码不会被压缩,主要是避免压缩带来的错误,比如JS错误 <!--wp-compress-html no compression--><!--wp-compress-html--> |
WordPress后台不压缩
试想如果WordPress后台被压缩了,那可真是惨不忍睹,所以要添加代码避免压缩wp后台。
1 2 3 4 5 |
//WordPress后台不压缩 if ( !is_admin() ) { ob_start("wp_compress_html_main"); } } |
文章代码不压缩
如果你的文章中有代码,你会发现它们都被压缩成一团了……这可不是我们想要的效果,所以添加下面代码避免这种情况的出现。
1 2 3 4 5 6 7 8 9 |
function unCompress($content) { if(preg_match_all('/(crayon-|<\/pre>)/i', $content, $matches)) { $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", "unCompress"); |
评论