我提出了两个包装函数:
function wp_enqueue_cdn_script( $handle, $src_cdn = false, $src_local = false, $deps = array(), $ver = false, $in_footer = false ) {
$cdnIsUp = get_transient( $handle . \'_script_cdn_is_up\' );
if ( $cdnIsUp ) {
wp_enqueue_script( $handle, $src_cdn, $deps, $ver, $in_footer );
} else {
$cdn_response = wp_remote_get( $src_cdn );
if ( is_wp_error( $cdn_response ) || wp_remote_retrieve_response_code( $cdn_response ) != \'200\' ) {
wp_enqueue_script( $handle, $src_local, $deps, $ver, $in_footer );
} else {
$cdnIsUp = set_transient( $handle . \'_script_cdn_is_up\', true, MINUTE_IN_SECONDS * 20 );
wp_enqueue_script( $handle, $src_cdn, $deps, $ver, $in_footer );
}
}
}
function wp_enqueue_cdn_style( $handle, $src_cdn = false, $src_local = false, $deps = array(), $ver = false, $media = \'all\' ) {
$cdnIsUp = get_transient( $handle . \'_style_cdn_is_up\' );
if ( $cdnIsUp ) {
wp_enqueue_style( $handle, $src_cdn, $deps, $ver, $media);
} else {
$cdn_response = wp_remote_get( $src_cdn );
if ( is_wp_error( $cdn_response ) || wp_remote_retrieve_response_code( $cdn_response ) != \'200\' ) {
wp_enqueue_style( $handle, $src_local, $deps, $ver, $media);
} else {
$cdnIsUp = set_transient( $handle . \'_style_cdn_is_up\', true, MINUTE_IN_SECONDS * 20 );
wp_enqueue_style( $handle, $src_cdn, $deps, $ver, $media);
}
}
}
但我想知道它是否真的有用:它会使服务器过载,我们假装如果服务器可以访问CDN,客户端也可以,这在现实世界中并不总是正确的。