| 1 |
<?php |
| 2 |
namespace ABlocks\Performance; |
| 3 |
|
| 4 |
if ( ! defined( 'ABSPATH' ) ) { |
| 5 |
exit; |
| 6 |
} |
| 7 |
|
| 8 |
use ABlocks\Helper; |
| 9 |
|
| 10 |
/** |
| 11 |
* Performance Suite — image loading optimizations for aBlocks blocks. |
| 12 |
* |
| 13 |
* Adds `loading="lazy"` + `decoding="async"` to images, while keeping the first |
| 14 |
* N images eager with `fetchpriority="high"` so the LCP image isn't deferred. |
| 15 |
* |
| 16 |
* Opt-in via `perf_lazy_images`. Operates on rendered block HTML (scoped to |
| 17 |
* aBlocks blocks) so no per-block markup changes are needed. |
| 18 |
*/ |
| 19 |
class ImageOptimizer { |
| 20 |
|
| 21 |
private $image_index = 0; |
| 22 |
private $eager_count = 1; |
| 23 |
|
| 24 |
public static function init() { |
| 25 |
if ( is_admin() ) { |
| 26 |
return; |
| 27 |
} |
| 28 |
$enabled = (bool) apply_filters( |
| 29 |
'ablocks/perf/perf_lazy_images', |
| 30 |
(bool) Helper::get_settings( 'perf_lazy_images', true ) |
| 31 |
); |
| 32 |
if ( ! $enabled ) { |
| 33 |
return; |
| 34 |
} |
| 35 |
$self = new self(); |
| 36 |
$self->eager_count = (int) apply_filters( |
| 37 |
'ablocks/perf/lcp_eager_count', |
| 38 |
(int) Helper::get_settings( 'perf_lcp_eager_count', 1 ) |
| 39 |
); |
| 40 |
add_filter( 'render_block', [ $self, 'process' ], 20, 2 ); |
| 41 |
} |
| 42 |
|
| 43 |
public function process( $content, $block ) { |
| 44 |
if ( empty( $block['blockName'] ) || false === strpos( $block['blockName'], 'ablocks' ) ) { |
| 45 |
return $content; |
| 46 |
} |
| 47 |
if ( false === strpos( $content, '<img' ) ) { |
| 48 |
return $content; |
| 49 |
} |
| 50 |
|
| 51 |
return preg_replace_callback( |
| 52 |
'/<img\b(?![^>]*\bloading=)[^>]*>/i', |
| 53 |
[ $this, 'rewrite_img' ], |
| 54 |
$content |
| 55 |
); |
| 56 |
} |
| 57 |
|
| 58 |
private function rewrite_img( $matches ) { |
| 59 |
$tag = $matches[0]; |
| 60 |
$this->image_index++; |
| 61 |
|
| 62 |
if ( $this->image_index <= $this->eager_count ) { |
| 63 |
// Likely-LCP images: load eagerly with high priority. |
| 64 |
$attrs = ' loading="eager" fetchpriority="high"'; |
| 65 |
} else { |
| 66 |
$attrs = ' loading="lazy"'; |
| 67 |
} |
| 68 |
|
| 69 |
if ( false === stripos( $tag, 'decoding=' ) ) { |
| 70 |
$attrs .= ' decoding="async"'; |
| 71 |
} |
| 72 |
|
| 73 |
return preg_replace( '/^<img\b/', '<img' . $attrs, $tag, 1 ); |
| 74 |
} |
| 75 |
} |
| 76 |
|