• 下班后只想安静的听一会歌

HTML压缩

WP教程 quanshui 7年前 (2016-08-23) 2959次浏览 已收录 1个评论

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");

GZIP压缩

//开启GZIP压缩
function gzip() {
	ob_start('ob_gzhandler');
}
if(!stristr($_SERVER['REQUEST_URI'], 'tinymce') && !ini_get('zlib.output_compression')) {
	add_action('init', 'gzip');
}

Gzip压缩JS和CSS

Gzip压缩CSS方法(以style.css文件为例)

  1. 将以下代码加入style.css文件的的头部:

  2. 将以下代码加入style.css 文件的的尾部:

    <?php if(extension_loaded('zlib')) {ob_end_flush();} ?>

  3. 将文件更名为:style.css.php

  4. 找到主题文件中引用style.css处,将其更名为:style.css.php

Gzip压缩JS方法:

  1. 步骤和压缩CSS文件一样,只是第1步的代码改为:

    <?php if ( extension_loaded('zlib') ) 
    {
       ob_start('ob_gzhandler');
    }
    header("Content-Type: text/javascript"); ?>

  2. 第2步与上方相同,第3步、第4步文件名对应修改即可。

喜欢 (0)
[]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(1)个小伙伴在吐槽
  1. 哈哈,不错????
    泉水2016-09-08 20:36 回复 Linux | Chrome 37.0.0.0