PluginProbe
aBlocks – Gutenberg Blocks, User Dashboard Builder, Popup Builder, Form Builder & Animation Builder / 2.10.0
aBlocks – Gutenberg Blocks, User Dashboard Builder, Popup Builder, Form Builder & Animation Builder v2.10.0
2.13.0 2.13.1 2.12.0 2.11.1 2.11.0 2.10.0 2.9.0 2.7.4 2.7.5 2.7.6 2.7.7 2.8.0 2.8.1 2.9.1 trunk 1.0 1.0-beta1 1.0-beta2 1.0-beta3 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.1.2 All 80 releases
ablocks / includes / performance / image-optimizer.php

image-optimizer.php in aBlocks – Gutenberg Blocks, User Dashboard Builder, Popup Builder, Form Builder & Animation Builder 2.10.0, at includes/performance/image-optimizer.php

76 lines 1.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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