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

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