settings = $settings;
}
/**
* Process HTML buffer to optimize scripts, styles, and markup.
*
* @param string $html Output HTML string.
* @return string
*/
public function process_html( $html ) {
if ( empty( $html ) ) {
return $html;
}
// 1. Google Fonts display=swap
if ( $this->settings->get( 'optimize_google_fonts', true ) ) {
$html = $this->optimize_google_fonts( $html );
}
// 2. JavaScript Optimization (Delay and/or Defer)
$do_delay = (bool) $this->settings->get( 'delay_js', false );
$do_defer = (bool) $this->settings->get( 'defer_js', true );
if ( $do_delay || $do_defer ) {
$html = $this->optimize_scripts( $html, $do_delay, $do_defer );
}
// 3. HTML Minification
if ( $this->settings->get( 'minify_html', false ) ) {
$html = $this->minify_html( $html );
}
return $html;
}
/**
* Add display=swap to Google/Bunny fonts links.
*
* @param string $html
* @return string
*/
private function optimize_google_fonts( $html ) {
$pattern = '/]+href=["\']([^"\']*(?:fonts\.googleapis\.com|fonts\.bunny\.net)[^"\']*)["\'][^>]*>/i';
return preg_replace_callback(
$pattern,
function( $matches ) {
$tag = $matches[0];
$url = $matches[1];
if ( false === stripos( $url, 'display=' ) ) {
$delim = ( false !== strpos( $url, '?' ) ) ? '&' : '?';
$new_url = $url . $delim . 'display=swap';
$tag = str_replace( $url, $new_url, $tag );
}
return $tag;
},
$html
);
}
/**
* Optimize JavaScript tags: Delay until user interaction or Defer.
*
* @param string $html
* @param bool $do_delay
* @param bool $do_defer
* @return string
*/
private function optimize_scripts( $html, $do_delay, $do_defer ) {
$excluded_raw = (string) $this->settings->get( 'excluded_js', '' );
$excluded = array_filter( array_map( 'trim', explode( "\n", $excluded_raw ) ) );
$excluded = apply_filters( 'awvb_excluded_scripts', $excluded );
$delay_raw = (string) $this->settings->get( 'delayed_js_scripts', '' );
$delay_keys = array_filter( array_map( 'trim', explode( "\n", $delay_raw ) ) );
$delayed_script_count = 0;
$pattern = '/';
}
}
// Check Defer (only for external src scripts)
if ( $do_defer && preg_match( '/\bsrc\s*=\s*["\']/i', $attributes ) ) {
if ( false === stripos( $attributes, 'defer' ) && false === stripos( $attributes, 'async' ) ) {
$attributes .= ' defer';
return '';
}
}
return $full_tag;
},
$html
);
// If any scripts were delayed, inject the micro-runner before