预缓存通常是用在高流量的网站上,其原理就是预先将页面的缓存加载好,便于下次直接访问缓存。这样做可以让网站有更好的网站体验。
但预缓存也有相应的弊端。如果你的服务器配置比较低的话,就会造成服务器暂时性的卡顿。因为要预先加载好缓存,所以造成短暂的cpu占用过高。
下面通过简单的一段php代码实现全站预缓存。
注意
使用此代码会出现发布和更新慢的情况。
//代码提取自preload-fullpage-cache
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );
if( !class_exists('PRELOAD_FULLPAGE_CACHE') ) {
class PRELOAD_FULLPAGE_CACHE
{
function __construct() {
add_action( 'wp_insert_post', array( $this, 'preload_desktop' ), 900, 3 ); // let's fetch the post very late
add_action( 'wp_insert_post', array( $this, 'preload_mobile' ), 990, 3 ); // let's fetch mobile version even later
add_action( 'wp_insert_post', array( $this, 'preload_amp' ), 999, 3 ); // let's fetch AMP version at last; only works on posts
}
// verison to fetch: desktop
// user-agent: Chrome 62 on a macOS Sierra 10.12.6
function preload_desktop( $post_ID, $post, $update ) {
$desktop_url = get_permalink( $post_ID );
$desktop_url_args = array(
'httpversion' => '1.1',
'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36',
);
wp_remote_get( $desktop_url, $desktop_url_args );
}
// version to fetch: mobile
// user-agent: iPhone 6 on iOS 9
function preload_mobile( $post_ID, $post, $update ) {
$mobile_url = get_permalink( $post_ID );
$mobile_url_args = array(
'httpversion' => '1.1',
'user-agent' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1',
);
wp_remote_get( $mobile_url, $mobile_url_args );
}
// version to fetch: amp
// user-agent: Chrome 62 on a macOS Sierra 10.12.6
function preload_amp( $post_ID, $post, $update ) {
$amp_url = get_permalink( $post_ID ) . 'amp/';
$amp_url_args = array(
'httpversion' => '1.1',
'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36',
);
wp_remote_get( $amp_url, $amp_url_args );
}
} // class PRELOAD_FULLPAGE_CACHE
// initialize the plugin by creating a new object
$GLOBALS['preload-fullpage-cache'] = new PRELOAD_FULLPAGE_CACHE();
} // if class_exists PRELOAD_FULLPAGE_CACHE
将此代码复制到functions.php中。其他的cms可以根据需要更改。