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

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