WordPress网站优化,无需插件纯代码压缩前端html网页

WordPress网站优化,无需插件纯代码压缩前端html网页,网站速度的快慢大多数取决于代码和服务器的配置,由于高额的服务器费用对于我们这种个人网站来说,服务器配置差不多就可以了,亿破姐网站服务器采用的是6核心12线程16G的配置,虽然配置不低,但是还是需要进行优化,可以优化的地方还是要坚持去优化的,毕竟谁都不想访问一个慢悠悠的网站,那么这里我就向大家分享下,如何通过使用纯代码来对WordPress前端html进行压缩,以达到给前台访问加速的目的。

首先将以下代码放入WordPress主题目录里的functions.php文件里面

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

加入以上代码后,打开网站前台,查看下源代码,看看最后一行是不是多了一个“压缩前的大小: xxx bytes; 压缩后的大小: xxx bytes; 节约:xxx%”的注释,如果有则说明生效了。

如果不想在网页源文件末尾有查看压缩信息,请删除以下代码

       $final=strlen($buffer_out);   
        $savings=($initial-$final)/$initial*100;   
        $savings=round($savings, 2);   
        $buffer_out.="\n<!--压缩前的大小: $initial bytes; 压缩后的大小: $final bytes; 节约:$savings% -->";   

有些特别的网站,可能会存在部分js代码被压缩后无法正常运行,那么可以使用以下代码解决,把代码放入指定的标签就不会被压缩。

<!--wp-compress-html--><!--wp-compress-html no compression-->
此处代码不会被压缩,主要是避免压缩带来的错误,请把不想被压缩的代码放入这里
<!--wp-compress-html no compression--><!--wp-compress-html-->

上面的代码不是放入functions.php文件里面的,需要在主题代码中有js的地方放入。

网站文章中有时候也需要插入代码,一篇文章需要插入几段代码了,如果文章中插入的代码也被压缩,是很影响用户阅读体验的,所有我们也要进行一下处理,同样将以下代码放入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");

以上就是WordPress网站优化,无需插件纯代码压缩前端html网页全部教程了。

版权声明:
作者:wangluo
链接:http://codeftp.com/?p=320
来源:源码分享网
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>