PluginProbe
Elementor Website Builder – more than just a page builder / 3.20.4
Elementor Website Builder – more than just a page builder v3.20.4
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.20.4, at modules/image-loading-optimization/module.php

377 lines 11.4 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
81 /**
82 * Stop WordPress core fetchpriority logic by setting the wp_high_priority_element_flag flag to false.
83 */
84 public function stop_core_fetchpriority_high_logic() {
85 // wp_high_priority_element_flag was only introduced in 6.3.0
86 if ( function_exists( 'wp_high_priority_element_flag' ) ) {
87 wp_high_priority_element_flag( false );
88 }
89 }
90
91 /**
92 * Set buffer to handle header and footer content.
93 */
94 public function set_buffer() {
95 ob_start( [ $this, 'handle_buffer_content' ] );
96 }
97
98 /**
99 * This function ensure that buffer if any is flushed before the content is called.
100 * This function behaves more like an action than a filter.
101 *
102 * @param string $content the content.
103 * @return string We simply return the content from parameter.
104 */
105 public function flush_header_buffer( $content ) {
106 $buffer_status = ob_get_status();
107
108 if ( ! empty( $buffer_status ) &&
109 1 === $buffer_status['type'] &&
110 get_class( $this ) . '::handle_buffer_content' === $buffer_status['name'] ) {
111 ob_end_flush();
112 }
113
114 return $content;
115 }
116
117 /**
118 * Callback to handle image optimization logic on buffered content.
119 *
120 * @param string $buffer Buffered content.
121 * @return string Content with optimized images.
122 */
123 public function handle_buffer_content( $buffer ) {
124 return $this->filter_images( $buffer );
125 }
126
127 /**
128 * Check for image in the content provided and apply optimization logic on them.
129 *
130 * @param string $content Content to be analyzed.
131 * @return string Content with optimized images.
132 */
133 private function filter_images( $content ) {
134 return preg_replace_callback(
135 '/<img\s[^>]+>/',
136 function ( $matches ) {
137 return $this->loading_optimization_image( $matches[0] );
138 },
139 $content
140 );
141 }
142
143 /**
144 * Apply loading optimization logic on the image.
145 *
146 * @param mixed $image Original image tag.
147 * @return string Optimized image.
148 */
149 public function loading_optimization_image( $image ) {
150 if ( isset( self::$image_visited[ $image ] ) ) {
151 return self::$image_visited[ $image ];
152 }
153
154 $optimized_image = $this->add_loading_optimization_attrs( $image );
155 self::$image_visited[ $image ] = $optimized_image;
156
157 return $optimized_image;
158 }
159
160 /**
161 * Adds optimization attributes to an `img` HTML tag.
162 *
163 * @param string $image The HTML `img` tag where the attribute should be added.
164 * @return string Converted `img` tag with optimization attributes added.
165 */
166 private function add_loading_optimization_attrs( $image ) {
167 $width = preg_match( '/ width=["\']([0-9]+)["\']/', $image, $match_width ) ? (int) $match_width[1] : null;
168 $height = preg_match( '/ height=["\']([0-9]+)["\']/', $image, $match_height ) ? (int) $match_height[1] : null;
169 $loading_val = preg_match( '/ loading=["\']([A-Za-z]+)["\']/', $image, $match_loading ) ? $match_loading[1] : null;
170 $fetchpriority_val = preg_match( '/ fetchpriority=["\']([A-Za-z]+)["\']/', $image, $match_fetchpriority ) ? $match_fetchpriority[1] : null;
171
172 // Images should have height and dimension width for the loading optimization attributes to be added.
173 if ( ! str_contains( $image, ' width="' ) || ! str_contains( $image, ' height="' ) ) {
174 return $image;
175 }
176
177 $optimization_attrs = $this->get_loading_optimization_attributes(
178 [
179 'width' => $width,
180 'height' => $height,
181 'loading' => $loading_val,
182 'fetchpriority' => $fetchpriority_val,
183 ]
184 );
185
186 if ( ! empty( $optimization_attrs['fetchpriority'] ) ) {
187 $image = str_replace( '<img', '<img fetchpriority="' . esc_attr( $optimization_attrs['fetchpriority'] ) . '"', $image );
188 }
189
190 if ( ! empty( $optimization_attrs['loading'] ) ) {
191 $image = str_replace( '<img', '<img loading="' . esc_attr( $optimization_attrs['loading'] ) . '"', $image );
192 }
193
194 return $image;
195 }
196
197 /**
198 * Return loading Loading optimization attributes for a image with give attribute.
199 *
200 * @param array $attr Existing image attributes.
201 * @return array Loading optimization attributes.
202 */
203 private function get_loading_optimization_attributes( $attr ) {
204 $loading_attrs = [];
205
206 // For any resources, width and height must be provided, to avoid layout shifts.
207 if ( ! isset( $attr['width'], $attr['height'] ) ) {
208 return $loading_attrs;
209 }
210
211 /*
212 * The key function logic starts here.
213 */
214 $maybe_in_viewport = null;
215 $increase_count = false;
216 $maybe_increase_count = false;
217
218 /*
219 * Logic to handle a `loading` attribute that is already provided.
220 *
221 * Copied from `wp_get_loading_optimization_attributes()`.
222 */
223 if ( isset( $attr['loading'] ) ) {
224 /*
225 * Interpret "lazy" as not in viewport. Any other value can be
226 * interpreted as in viewport (realistically only "eager" or `false`
227 * to force-omit the attribute are other potential values).
228 */
229 if ( 'lazy' === $attr['loading'] ) {
230 $maybe_in_viewport = false;
231 } else {
232 $maybe_in_viewport = true;
233 }
234 }
235
236 // Logic to handle a `fetchpriority` attribute that is already provided.
237 $has_fetchpriority_high_attr = ( isset( $attr['fetchpriority'] ) && 'high' === $attr['fetchpriority'] );
238
239 /*
240 * Handle cases where a `fetchpriority="high"` has already been set.
241 *
242 * Copied from `wp_get_loading_optimization_attributes()`.
243 */
244 if ( $has_fetchpriority_high_attr ) {
245 /*
246 * If the image was already determined to not be in the viewport (e.g.
247 * from an already provided `loading` attribute), trigger a warning.
248 * Otherwise, the value can be interpreted as in viewport, since only
249 * the most important in-viewport image should have `fetchpriority` set
250 * to "high".
251 */
252 if ( false === $maybe_in_viewport ) {
253 _doing_it_wrong(
254 __FUNCTION__,
255 esc_html__( 'An image should not be lazy-loaded and marked as high priority at the same time.', 'elementor' ),
256 ''
257 );
258 /*
259 * Set `fetchpriority` here for backward-compatibility as we should
260 * not override what a developer decided, even though it seems
261 * incorrect.
262 */
263 $loading_attrs['fetchpriority'] = 'high';
264 } else {
265 $maybe_in_viewport = true;
266 }
267 }
268
269 if ( null === $maybe_in_viewport && ! is_admin() ) {
270 $content_media_count = $this->increase_content_media_count( 0 );
271 $increase_count = true;
272 if ( $content_media_count < $this->omit_threshold ) {
273 $maybe_in_viewport = true;
274 } else {
275 $maybe_in_viewport = false;
276 }
277 }
278
279 if ( $maybe_in_viewport ) {
280 $loading_attrs = $this->maybe_add_fetchpriority_high_attr( $loading_attrs, $attr );
281 } else {
282 $loading_attrs['loading'] = 'lazy';
283 }
284
285 if ( $increase_count ) {
286 $this->increase_content_media_count();
287 } elseif ( $maybe_increase_count ) {
288 if ( $this->get_min_priority_img_pixels() <= $attr['width'] * $attr['height'] ) {
289 $this->increase_content_media_count();
290 }
291 }
292
293 return $loading_attrs;
294 }
295
296 /**
297 * Helper to get the minimum threshold for number of pixels an image needs to have to be considered "priority".
298 *
299 * @return int The minimum number of pixels (width * height). Default is 50000.
300 */
301 private function get_min_priority_img_pixels() {
302 /**
303 * Filter the minimum pixel threshold used to determine if an image should have fetchpriority="high" applied.
304 *
305 * @see https://developer.wordpress.org/reference/hooks/wp_min_priority_img_pixels/
306 *
307 * @param int $pixels The minimum number of pixels (with * height).
308 * @return int The filtered value.
309 */
310 return apply_filters( 'elementor/image-loading-optimization/min_priority_img_pixels', $this->min_priority_img_pixels );
311 }
312
313 /**
314 * Keeps a count of media image.
315 *
316 * @param int $amount Amount by which count must be increased.
317 * @return int current image count.
318 */
319 private function increase_content_media_count( $amount = 1 ) {
320 static $content_media_count = 0;
321
322 $content_media_count += $amount;
323
324 return $content_media_count;
325 }
326
327 /**
328 * Determines whether to add `fetchpriority='high'` to loading attributes.
329 *
330 * @param array $loading_attrs Array of the loading optimization attributes for the element.
331 * @param array $attr Array of the attributes for the element.
332 * @return array Updated loading optimization attributes for the element.
333 */
334 private function maybe_add_fetchpriority_high_attr( $loading_attrs, $attr ) {
335 if ( isset( $attr['fetchpriority'] ) ) {
336 if ( 'high' === $attr['fetchpriority'] ) {
337 $loading_attrs['fetchpriority'] = 'high';
338 $this->high_priority_element_flag( false );
339 }
340
341 return $loading_attrs;
342 }
343
344 // Lazy-loading and `fetchpriority="high"` are mutually exclusive.
345 if ( isset( $loading_attrs['loading'] ) && 'lazy' === $loading_attrs['loading'] ) {
346 return $loading_attrs;
347 }
348
349 if ( ! $this->high_priority_element_flag() ) {
350 return $loading_attrs;
351 }
352
353 if ( $this->get_min_priority_img_pixels() <= $attr['width'] * $attr['height'] ) {
354 $loading_attrs['fetchpriority'] = 'high';
355 $this->high_priority_element_flag( false );
356 }
357
358 return $loading_attrs;
359 }
360
361 /**
362 * Accesses a flag that indicates if an element is a possible candidate for `fetchpriority='high'`.
363 *
364 * @param bool $value Optional. Used to change the static variable. Default null.
365 * @return bool Returns true if high-priority element was marked already, otherwise false.
366 */
367 private function high_priority_element_flag( $value = null ) {
368 static $high_priority_element = true;
369
370 if ( is_bool( $value ) ) {
371 $high_priority_element = $value;
372 }
373
374 return $high_priority_element;
375 }
376 }
377