WordPress免插件优化压缩网页代码

到底压缩了什么

压缩主要是去除源码中的空格回车等一个无关紧要的符号,使的打开的网页的代码文件减小。
有效的压缩网站代码,可以加快网站的打开速度,减少对服务器的消耗。

怎么压缩

把以下代码添加到WordPress的主题文件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" );

以上代码的第二段和第三段都有相应的作用注释,起到压缩作用的代码是第一段,所以可以根据自己的需要修改。

压缩注释问题

由于压缩的会去掉回车可能会造成"//这是被注释的内容"这种注释后的其他代码也被注释掉的情况,所以建议把源码中的"//"注释改成"/**/",或者删除。
如何不让部分代码不被压缩呢,如下格式:

<!--wp-compress-html--><!--wp-compress-html no compression-->
此处代码不会被压缩,主要是避免压缩带来的错误,比如JS错误
<!--wp-compress-html no compression--><!--wp-compress-html-->

Tips:建议配合wp-super-cache插件来使用效果更佳。

相关推荐

发表评论

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

微信扫一扫,分享到朋友圈

WordPress免插件优化压缩网页代码
返回顶部

显示

忘记密码?

显示

显示

获取验证码

Close