PluginProbe
Elementor Website Builder – more than just a page builder / 3.19.0-beta1
Elementor Website Builder – more than just a page builder v3.19.0-beta1
4.3.0-beta2 4.3.0-beta1 4.2.4 4.2.3 4.2.2 4.2.1 4.2.0 4.1.5 4.2.0-beta2 4.2.0-dev2 4.2.0-beta1 4.1.4 4.1.3 4.1.2 4.1.1 4.1.0 4.1.0-beta3 4.1.0-dev3 4.0.9 4.1.0-beta2 4.1.0-dev2 4.0.8 4.1.0-beta1 4.1.0-dev1 4.0.7 All 451 releases
elementor / modules / image-loading-optimization / module.php

module.php in Elementor Website Builder – more than just a page builder 3.19.0-beta1, at modules/image-loading-optimization/module.php

380 lines 11.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace Elementor\Modules\ImageLoadingOptimization;
3
4 use Elementor\Core\Base\Module as BaseModule;
5 use Elementor\Core\Experiments\Manager as Experiments_Manager;
6
7 if ( ! defined( 'ABSPATH' ) ) {
8 exit; // Exit if accessed directly
9 }
10
11 class Module extends BaseModule {
12 /**
13 * @var string The experiment name.
14 */
15 const EXPERIMENT_NAME = 'e_image_loading_optimization';
16
17 /**
18 * @var int Minimum square-pixels threshold.
19 */
20 private $min_priority_img_pixels = 50000;
21
22 /**
23 * @var int The number of content media elements to not lazy-load.
24 */
25 private $omit_threshold = 3;
26
27 /**
28 * @var array Keep a track of images for which loading optimization strategy were computed.
29 */
30 private static $image_visited = [];
31
32 /**
33 * Get Module name.
34 */
35 public function get_name() {
36 return 'image-loading-optimization';
37 }
38
39 /**
40 * Get experimental data.
41 *
42 * @return array Experimental settings.
43 */
44 public static function get_experimental_data() {
45 return [
46 'name' => static::EXPERIMENT_NAME,
47 'title' => esc_html__( 'Optimize Image Loading', 'elementor' ),
48 'tag' => esc_html__( 'Performance', 'elementor' ),
49 'description' => sprintf(
50 /* translators: 1: fetchpriority attribute, 2: lazy loading attribute. */
51 esc_html__( 'Applying %1$s on LCP image and %2$s on images below the fold to improve performance scores.', 'elementor' ),
52 '<code>fetchpriority="high"</code>',
53 '<code>loading="lazy"</code>'
54 ),
55 'generator_tag' => true,
56 'release_status' => Experiments_Manager::RELEASE_STATUS_STABLE,
57 'default' => Experiments_Manager::STATE_ACTIVE,
58 ];
59 }
60
61 /**
62 * Constructor.
63 */
64 public function __construct() {
65 parent::__construct();
66
67 // Stop wp core logic.
68 add_action( 'init', [ $this, 'stop_core_fetchpriority_high_logic' ] );
69 add_filter( 'wp_lazy_loading_enabled', '__return_false' );
70
71 // Run optimization logic on header.
72 add_action( 'get_header', [ $this, 'set_buffer' ] );
73
74 // Ensure buffer is flushed (if any) before the content logic.
75 add_filter( 'the_content', [ $this, 'flush_header_buffer' ], 0 );
76
77 // Run optimization logic on content.
78 add_filter( 'wp_content_img_tag', [ $this, 'loading_optimization_image' ] );
79
80 // Run optimization logic on footer. Flushing of footer buffer will be handled by PHP script end default logic.
81 add_action( 'get_footer', [ $this, 'set_buffer' ] );
82 }
83
84 /**
85 * Stop WordPress core fetchpriority logic by setting the wp_high_priority_element_flag flag to false.
86 */
87 public function stop_core_fetchpriority_high_logic() {
88 // wp_high_priority_element_flag was only introduced in 6.3.0
89 if ( function_exists( 'wp_high_priority_element_flag' ) ) {
90 wp_high_priority_element_flag( false );
91 }
92 }
93
94 /**
95 * Set buffer to handle header and footer content.
96 */
97 public function set_buffer() {
98 ob_start( [ $this, 'handle_buffer_content' ] );
99 }
100
101 /**
102 * This function ensure that buffer if any is flushed before the content is called.
103 * This function behaves more like an action than a filter.
104 *
105 * @param string $content the content.
106 * @return string We simply return the content from parameter.
107 */
108 public function flush_header_buffer( $content ) {
109 $buffer_status = ob_get_status();
110
111 if ( ! empty( $buffer_status ) &&
112 1 === $buffer_status['type'] &&
113 get_class( $this ) . '::handle_buffer_content' === $buffer_status['name'] ) {
114 ob_end_flush();
115 }
116
117 return $content;
118 }
119
120 /**
121 * Callback to handle image optimization logic on buffered content.
122 *
123 * @param string $buffer Buffered content.
124 * @return string Content with optimized images.
125 */
126 public function handle_buffer_content( $buffer ) {
127 return $this->filter_images( $buffer );
128 }
129
130 /**
131 * Check for image in the content provided and apply optimization logic on them.
132 *
133 * @param string $content Content to be analyzed.
134 * @return string Content with optimized images.
135 */
136 private function filter_images( $content ) {
137 return preg_replace_callback(
138 '/<img\s[^>]+>/',
139 function ( $matches ) {
140 return $this->loading_optimization_image( $matches[0] );
141 },
142 $content
143 );
144 }
145
146 /**
147 * Apply loading optimization logic on the image.
148 *
149 * @param mixed $image Original image tag.
150 * @return string Optimized image.
151 */
152 public function loading_optimization_image( $image ) {
153 if ( isset( self::$image_visited[ $image ] ) ) {
154 return self::$image_visited[ $image ];
155 }
156
157 $optimized_image = $this->add_loading_optimization_attrs( $image );
158 self::$image_visited[ $image ] = $optimized_image;
159
160 return $optimized_image;
161 }
162
163 /**
164 * Adds optimization attributes to an `img` HTML tag.
165 *
166 * @param string $image The HTML `img` tag where the attribute should be added.
167 * @return string Converted `img` tag with optimization attributes added.
168 */
169 private function add_loading_optimization_attrs( $image ) {
170 $width = preg_match( '/ width=["\']([0-9]+)["\']/', $image, $match_width ) ? (int) $match_width[1] : null;
171 $height = preg_match( '/ height=["\']([0-9]+)["\']/', $image, $match_height ) ? (int) $match_height[1] : null;
172 $loading_val = preg_match( '/ loading=["\']([A-Za-z]+)["\']/', $image, $match_loading ) ? $match_loading[1] : null;
173 $fetchpriority_val = preg_match( '/ fetchpriority=["\']([A-Za-z]+)["\']/', $image, $match_fetchpriority ) ? $match_fetchpriority[1] : null;
174
175 // Images should have height and dimension width for the loading optimization attributes to be added.
176 if ( ! str_contains( $image, ' width="' ) || ! str_contains( $image, ' height="' ) ) {
177 return $image;
178 }
179
180 $optimization_attrs = $this->get_loading_optimization_attributes(
181 [
182 'width' => $width,
183 'height' => $height,
184 'loading' => $loading_val,
185 'fetchpriority' => $fetchpriority_val,
186 ]
187 );
188
189 if ( ! empty( $optimization_attrs['fetchpriority'] ) ) {
190 $image = str_replace( '<img', '<img fetchpriority="' . esc_attr( $optimization_attrs['fetchpriority'] ) . '"', $image );
191 }
192
193 if ( ! empty( $optimization_attrs['loading'] ) ) {
194 $image = str_replace( '<img', '<img loading="' . esc_attr( $optimization_attrs['loading'] ) . '"', $image );
195 }
196
197 return $image;
198 }
199
200 /**
201 * Return loading Loading optimization attributes for a image with give attribute.
202 *
203 * @param array $attr Existing image attributes.
204 * @return array Loading optimization attributes.
205 */
206 private function get_loading_optimization_attributes( $attr ) {
207 $loading_attrs = [];
208
209 // For any resources, width and height must be provided, to avoid layout shifts.
210 if ( ! isset( $attr['width'], $attr['height'] ) ) {
211 return $loading_attrs;
212 }
213
214 /*
215 * The key function logic starts here.
216 */
217 $maybe_in_viewport = null;
218 $increase_count = false;
219 $maybe_increase_count = false;
220
221 /*
222 * Logic to handle a `loading` attribute that is already provided.
223 *
224 * Copied from `wp_get_loading_optimization_attributes()`.
225 */
226 if ( isset( $attr['loading'] ) ) {
227 /*
228 * Interpret "lazy" as not in viewport. Any other value can be
229 * interpreted as in viewport (realistically only "eager" or `false`
230 * to force-omit the attribute are other potential values).
231 */
232 if ( 'lazy' === $attr['loading'] ) {
233 $maybe_in_viewport = false;
234 } else {
235 $maybe_in_viewport = true;
236 }
237 }
238
239 // Logic to handle a `fetchpriority` attribute that is already provided.
240 $has_fetchpriority_high_attr = ( isset( $attr['fetchpriority'] ) && 'high' === $attr['fetchpriority'] );
241
242 /*
243 * Handle cases where a `fetchpriority="high"` has already been set.
244 *
245 * Copied from `wp_get_loading_optimization_attributes()`.
246 */
247 if ( $has_fetchpriority_high_attr ) {
248 /*
249 * If the image was already determined to not be in the viewport (e.g.
250 * from an already provided `loading` attribute), trigger a warning.
251 * Otherwise, the value can be interpreted as in viewport, since only
252 * the most important in-viewport image should have `fetchpriority` set
253 * to "high".
254 */
255 if ( false === $maybe_in_viewport ) {
256 _doing_it_wrong(
257 __FUNCTION__,
258 esc_html__( 'An image should not be lazy-loaded and marked as high priority at the same time.', 'elementor' ),
259 ''
260 );
261 /*
262 * Set `fetchpriority` here for backward-compatibility as we should
263 * not override what a developer decided, even though it seems
264 * incorrect.
265 */
266 $loading_attrs['fetchpriority'] = 'high';
267 } else {
268 $maybe_in_viewport = true;
269 }
270 }
271
272 if ( null === $maybe_in_viewport && ! is_admin() ) {
273 $content_media_count = $this->increase_content_media_count( 0 );
274 $increase_count = true;
275 if ( $content_media_count < $this->omit_threshold ) {
276 $maybe_in_viewport = true;
277 } else {
278 $maybe_in_viewport = false;
279 }
280 }
281
282 if ( $maybe_in_viewport ) {
283 $loading_attrs = $this->maybe_add_fetchpriority_high_attr( $loading_attrs, $attr );
284 } else {
285 $loading_attrs['loading'] = 'lazy';
286 }
287
288 if ( $increase_count ) {
289 $this->increase_content_media_count();
290 } elseif ( $maybe_increase_count ) {
291 if ( $this->get_min_priority_img_pixels() <= $attr['width'] * $attr['height'] ) {
292 $this->increase_content_media_count();
293 }
294 }
295
296 return $loading_attrs;
297 }
298
299 /**
300 * Helper to get the minimum threshold for number of pixels an image needs to have to be considered "priority".
301 *
302 * @return int The minimum number of pixels (width * height). Default is 50000.
303 */
304 private function get_min_priority_img_pixels() {
305 /**
306 * Filter the minimum pixel threshold used to determine if an image should have fetchpriority="high" applied.
307 *
308 * @see https://developer.wordpress.org/reference/hooks/wp_min_priority_img_pixels/
309 *
310 * @param int $pixels The minimum number of pixels (with * height).
311 * @return int The filtered value.
312 */
313 return apply_filters( 'elementor/image-loading-optimization/min_priority_img_pixels', $this->min_priority_img_pixels );
314 }
315
316 /**
317 * Keeps a count of media image.
318 *
319 * @param int $amount Amount by which count must be increased.
320 * @return int current image count.
321 */
322 private function increase_content_media_count( $amount = 1 ) {
323 static $content_media_count = 0;
324
325 $content_media_count += $amount;
326
327 return $content_media_count;
328 }
329
330 /**
331 * Determines whether to add `fetchpriority='high'` to loading attributes.
332 *
333 * @param array $loading_attrs Array of the loading optimization attributes for the element.
334 * @param array $attr Array of the attributes for the element.
335 * @return array Updated loading optimization attributes for the element.
336 */
337 private function maybe_add_fetchpriority_high_attr( $loading_attrs, $attr ) {
338 if ( isset( $attr['fetchpriority'] ) ) {
339 if ( 'high' === $attr['fetchpriority'] ) {
340 $loading_attrs['fetchpriority'] = 'high';
341 $this->high_priority_element_flag( false );
342 }
343
344 return $loading_attrs;
345 }
346
347 // Lazy-loading and `fetchpriority="high"` are mutually exclusive.
348 if ( isset( $loading_attrs['loading'] ) && 'lazy' === $loading_attrs['loading'] ) {
349 return $loading_attrs;
350 }
351
352 if ( ! $this->high_priority_element_flag() ) {
353 return $loading_attrs;
354 }
355
356 if ( $this->get_min_priority_img_pixels() <= $attr['width'] * $attr['height'] ) {
357 $loading_attrs['fetchpriority'] = 'high';
358 $this->high_priority_element_flag( false );
359 }
360
361 return $loading_attrs;
362 }
363
364 /**
365 * Accesses a flag that indicates if an element is a possible candidate for `fetchpriority='high'`.
366 *
367 * @param bool $value Optional. Used to change the static variable. Default null.
368 * @return bool Returns true if high-priority element was marked already, otherwise false.
369 */
370 private function high_priority_element_flag( $value = null ) {
371 static $high_priority_element = true;
372
373 if ( is_bool( $value ) ) {
374 $high_priority_element = $value;
375 }
376
377 return $high_priority_element;
378 }
379 }
380