settings = Settings::get_settings();
add_action( 'init', [ $this, 'maybe_control_heartbeat' ], 1 );
add_filter( 'heartbeat_settings', [ $this, 'filter_heartbeat_settings' ] );
add_action( 'wp_head', [ $this, 'output_resource_hints' ], 1 );
add_filter( 'ezcache_before_save_cache', [ $this, 'lazy_load_html' ], 20 );
add_filter( 'ezcache_before_save_cache', [ $this, 'remove_query_strings' ], 30 );
add_filter( 'ezcache_before_save_cache', [ $this, 'rewrite_cdn_urls' ], 40 );
add_filter( 'ezcache_before_save_cache', [ $this, 'defer_js' ], 50 );
}
/**
* Disable or throttle the WP Heartbeat API based on settings.
*/
public function maybe_control_heartbeat() {
if ( empty( $this->settings->heartbeat_control ) ) {
return;
}
$mode = isset( $this->settings->heartbeat_mode ) ? $this->settings->heartbeat_mode : 'reduce';
if ( 'disable' === $mode ) {
wp_deregister_script( 'heartbeat' );
}
}
/**
* Slow the heartbeat tick interval down (default 60s) when "reduce" mode is on.
*
* @param array $settings
* @return array
*/
public function filter_heartbeat_settings( $settings ) {
if ( empty( $this->settings->heartbeat_control ) ) {
return $settings;
}
$mode = isset( $this->settings->heartbeat_mode ) ? $this->settings->heartbeat_mode : 'reduce';
if ( 'reduce' === $mode ) {
$settings['interval'] = 60;
$settings['minimalInterval'] = 60;
}
return $settings;
}
/**
* Output `` and `` tags
* configured by the user.
*/
public function output_resource_hints() {
if ( ! empty( $this->settings->dns_prefetch ) ) {
$hosts = preg_split( "/\r\n|\r|\n/", trim( $this->settings->dns_prefetch ), -1, PREG_SPLIT_NO_EMPTY );
foreach ( $hosts as $host ) {
$host = esc_url( trim( $host ) );
if ( $host ) {
echo "\n";
}
}
}
if ( ! empty( $this->settings->preconnect ) ) {
$hosts = preg_split( "/\r\n|\r|\n/", trim( $this->settings->preconnect ), -1, PREG_SPLIT_NO_EMPTY );
foreach ( $hosts as $host ) {
$host = esc_url( trim( $host ) );
if ( $host ) {
echo "\n";
}
}
}
}
/**
* Add native lazy-loading to images and iframes that don't already opt out.
*
* @param string $html
* @return string
*/
public function lazy_load_html( $html ) {
if ( empty( $this->settings->lazy_load_images ) && empty( $this->settings->lazy_load_iframes ) ) {
return $html;
}
if ( ! empty( $this->settings->lazy_load_images ) ) {
$html = preg_replace_callback(
'#
]*)>#i',
function ( $match ) {
$attrs = $match[1];
if ( false !== stripos( $attrs, 'data-no-lazy' ) || preg_match( '/loading\s*=\s*["\'][^"\']*["\']/i', $attrs ) ) {
return $match[0];
}
return '
';
},
$html
);
}
if ( ! empty( $this->settings->lazy_load_iframes ) ) {
$html = preg_replace_callback(
'#