文章目录[隐藏]
HTML压缩
直接上代码:
/*压缩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');
-
压缩页面会衍生出一些问题,比如说,某些位置的某些特效失效了,如果你主题文件中某一段代码不想被压缩,或者文章中有不想压缩的内容,可手动添加不压缩代码段
解决方法:
<!--wp-compress-html--><!--wp-compress-html no compression--> 此处代码不会被压缩,主要是避免压缩带来的错误,比如JS错误(//文章中在文本模式下添加) <!--wp-compress-html no compression--><!--wp-compress-html-->
-
顺带再说一个技巧,如果博客使用了Crayon Syntax Highlighter高亮插件,那么启用代码压缩之后,你会发现在文章页面双击代码切换到纯文本模式时,会发现代码全挤在一团了!好吧,全都给压缩了,尴尬中…
解决办法:
将以下代码加入到主题functions.php当中,当检测到文章内容中有代码标签时,文章内容不会被压缩:
//判断文章中是否有代码,有代码不压缩 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");
-
HTML压缩率查看:右键点击源代码底部即可查看压缩信息
-
HTML请求次数检测:http://www.timle.cn/page-speed.html 点击前往
GZIP压缩
//开启GZIP压缩 function gzip() { ob_start('ob_gzhandler'); } if(!stristr($_SERVER['REQUEST_URI'], 'tinymce') && !ini_get('zlib.output_compression')) { add_action('init', 'gzip'); }
-
GZIP压缩率检测:http://tool.chinaz.com/Gzips/ 点击前往
Gzip压缩JS和CSS
Gzip压缩CSS方法(以style.css文件为例)
-
将以下代码加入style.css文件的的头部:
-
将以下代码加入style.css 文件的的尾部:
<?php if(extension_loaded('zlib')) {ob_end_flush();} ?>
-
将文件更名为:style.css.php
-
找到主题文件中引用style.css处,将其更名为:style.css.php
Gzip压缩JS方法:
-
步骤和压缩CSS文件一样,只是第1步的代码改为:
<?php if ( extension_loaded('zlib') ) { ob_start('ob_gzhandler'); } header("Content-Type: text/javascript"); ?>
-
第2步与上方相同,第3步、第4步文件名对应修改即可。