settings = $settings; } /** * Register hooks. * * @return void */ public function register() { add_filter( 'acelora_site_accelerator_optimize_html', array( $this, 'optimize_html' ), 30 ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_delay_loader' ) ); } /** * Optimize JS in HTML. * * @param string $html HTML. * @return string */ public function optimize_html( $html ) { if ( $this->settings->get( 'js.minify', 1 ) ) { $html = preg_replace_callback( '#]*\bsrc=)([^>]*)>(.*?)#is', function ( $matches ) { $type = $this->attribute( ''; }, $html ); } $html = $this->optimize_script_tags( $html ); return $html; } /** * Enqueue the delay loader via WordPress' script API. * * @return void */ public function enqueue_delay_loader() { if ( ! $this->settings->get( 'js.delay', 0 ) ) { return; } wp_register_script( 'acelora-delay-loader', false, array(), ACELORA_SITE_ACCELERATOR_VERSION, true ); wp_enqueue_script( 'acelora-delay-loader' ); wp_add_inline_script( 'acelora-delay-loader', $this->delay_loader_code() ); } /** * Minify JavaScript conservatively. * * @param string $js JavaScript. * @return string */ public function minify( $js ) { $js = preg_replace( '#/\*[\s\S]*?\*/#', '', $js ); $js = preg_replace( '#(^|[^:])//.*$#m', '$1', $js ); $js = preg_replace( '/\s+/', ' ', $js ); $js = preg_replace( '/\s*([{}();,:=+\-*\/<>])\s*/', '$1', $js ); return trim( $js ); } /** * Add async, defer, or delay handling to external scripts. * * @param string $html HTML. * @return string */ private function optimize_script_tags( $html ) { return preg_replace_callback( '#]*)src=["\']([^"\']+)["\']([^>]*)>#i', function ( $matches ) { $tag = $matches[0]; $src = html_entity_decode( $matches[2], ENT_QUOTES ); if ( $this->is_excluded( $src ) || false !== stripos( $tag, ' type="module"' ) || false !== stripos( $tag, ' nomodule' ) ) { return $tag; } if ( $this->settings->get( 'js.delay', 0 ) ) { $attrs = trim( preg_replace( '/\s+src=["\'][^"\']+["\']/i', '', ''; } if ( $this->settings->get( 'js.async', 0 ) && false === stripos( $tag, ' async' ) && false === stripos( $tag, ' defer' ) ) { return str_replace( '