WordPress网站加速心得

发布于 2020-02-28  744 次阅读


效果

总的来说,将原本的waiting加download时间从5s缩短到了大概1s左右,对于香港的主机来说还是比较大的提升的

图片cdn加速

由于图片的数量和体积比较大,我将所有图片使用jsdelivr+github的免费cdn服务,速度提升很快,本地的文件替换采用了两段代码,如下


define('CDN_HOST','https://jsdelivr.amogu.cn/gh/lzusa/wordpresscdn2@1.0'); add_filter('the_content','z_cdn_content'); function z_cdn_content(content){ return str_replace(home_url().'/wp-content/uploads', CDN_HOST.'/',content); } add_filter('wp_get_attachment_url','z_get_attachment_url',10,2); function z_get_attachment_url(url,post_id){ return str_replace(home_url(), CDN_HOST, url); } //静态文件CDN加速 if ( !is_admin() ) { add_action('wp_loaded','yuncai_ob_start'); function yuncai_ob_start() { ob_start('yuncai_qiniu_cdn_replace'); } function yuncai_qiniu_cdn_replace(html){ local_host = 'https://lzusaaa.com/wp-content/themes/Sakura/images'; //博客域名qiniu_host = 'https://jsdelivr.amogu.cn/gh/lzusa/wordpresscdn2@4.0'; //CDN域名 cdn_exts = 'css|js|png|jpg|jpeg|gif|ico'; //扩展名(使用|分隔)cdn_dirs = ''; //目录(使用|分隔) cdn_dirs = str_replace('-', '\-',cdn_dirs); if (cdn_dirs) {regex = '/' . str_replace('/', '\/', local_host) . '\/((' .cdn_dirs . ')\/[^\s\?\\\'\"\;\>\<]{1,}.(' . cdn_exts . '))([\"\\\'\s\?]{1})/';html = preg_replace(regex,qiniu_host . '/14', html); } else {regex = '/' . str_replace('/', '\/', local_host) . '\/([^\s\?\\\'\"\;\>\<]{1,}.(' .cdn_exts . '))([\"\\\'\s\?]{1})/'; html = preg_replace(regex, qiniu_host . '/13',html); } return $html; } }

这样的目的是给某些特定的文件夹进行加速的同时不会对某些静态文件产生不利影响,具体做法这里不赘述了。

js加速

js的加速采用了以下的代码

if(!is_admin()){
wp_deregister_script('jquery');
wp_register_script('jquery', ("http://upcdn.b0.upaiyun.com/libs/jquery/jquery-1.8.3.min.js"), false, '');
wp_enqueue_script('jquery');
}

禁用google字体

class Disable_Google_Fonts {
public function __construct() {
add_filter( 'gettext_with_context', array( this, 'disable_open_sans' ), 888, 4 );
}
public function disable_open_sans(translations, text,context, domain ) {
if ( 'Open Sans font: on or off' ==context && 'on' == text ) {translations = 'off';
}
return translations;
}
}disable_google_fonts = new Disable_Google_Fonts;

wp Super Cacha插件

采用该插件之前,直接对原有的动态链接更改为现在的固定链接样式,采用了redirection插件的自动重定向,就可以没有顾虑的直接更改网页链接格式了。
之后对于Super Cacha的配置基本参照网上的一般配置方式

以上