之前小舞发布了一篇就是前端代码压缩的文章,效果图如下daimayasuo,就是将首页的空格,js,css等全部压缩,将首页变的更加密集,对于加载速度也是有帮助,不过之前小舞给大家带来的是wordpress两款代码前端压缩插件,今天小舞给大家带来代码版的压缩,这样我们也能剩下一个插件就可以达到压缩的效果。

方法有两个,大家多测试,挑选自己合适的用

首先是代码1

  1. //压缩
  2. function wpjam_minify_html($html) {
  3.     $search = array(
  4.         '/>[^S ]+/s',  // 删除标签后面空格
  5.         '/[^S ]+</s',  // 删除标签前面的空格
  6.         '/(s)+/s'       // 将多个空格合并成一个
  7.     );
  8.     $replace = array(
  9.         '>',
  10.         '<',
  11.         '\1'
  12.     );
  13.     $html = preg_replace($search$replace$html);
  14.     return $html;
  15. }
  16. if(!is_admin()){
  17.     add_action("wp_loaded", 'wp_loaded_minify_html');
  18.     function wp_loaded_minify_html(){
  19.         ob_start('wpjam_minify_html');
  20.     }
  21. }

代码2:这段代码是由wpmee博主研究出来的,非常感谢作者的勤劳成果,但是这个代码好像有些问题,有些主题可以使用,有些就不可以使用,小舞现在还没搞明白是怎么回事,准备把WP-HTML-Compression插件直接include到现在的主题里边试试效果

  1. /*  
  2. *压缩html代码  
  3. * http://www.wpmee.com/wp-compress-html ‎  
  4. */  
  5. function wp_compress_html()   
  6. {   
  7.   
  8. function wp_compress_html_main ($buffer)   
  9. {   
  10.     $initial=strlen($buffer);   
  11.     $buffer=explode("<!--wp-compress-html-->"$buffer);   
  12.     $count=count ($buffer);   
  13.   
  14.     for ($i = 0; $i <= $count$i++)   
  15.     {   
  16.         if (stristr($buffer[$i], '<!--wp-compress-html no compression-->'))   
  17.         {   
  18.             $buffer[$i]=(str_replace("<!--wp-compress-html no compression-->"" "$buffer[$i]));   
  19.         }   
  20.         else  
  21.         {   
  22.             $buffer[$i]=(str_replace("t"" "$buffer[$i]));   
  23.             $buffer[$i]=(str_replace("nn""n"$buffer[$i]));   
  24.             $buffer[$i]=(str_replace("n"""$buffer[$i]));   
  25.             $buffer[$i]=(str_replace("r"""$buffer[$i]));   
  26.   
  27.             while (stristr($buffer[$i], '  '))   
  28.             {   
  29.             $buffer[$i]=(str_replace("  "" "$buffer[$i]));   
  30.             }   
  31.         }   
  32.         $buffer_out.=$buffer[$i];   
  33.     }   
  34.     //$final=strlen($buffer_out);   
  35.     //$savings=($initial-$final)/$initial*100;   
  36.     //$savings=round($savings, 2);   
  37.     //$buffer_out.="n<!--压缩前的大小: $initial bytes; 压缩后的大小: $final bytes; 节约:$savings% -->";   
  38.     return $buffer_out;   
  39. }   
  40.   
  41. ob_start("wp_compress_html_main");   
  42. }   
  43.   
  44. add_action('get_header', 'wp_compress_html');  

以上两款插件你只需要任意的挑选一款代码加入到你当前使用主题文件的function.php中保存就可以使用了!!!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。