class-lazy.php
19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
<?php
/**
* Lazy load images class: Lazy
*
* @since 3.2.0
* @package Smush\Core\Modules
*/
namespace Smush\Core\Modules;
if ( ! defined( 'WPINC' ) ) {
die;
}
/**
* Class Lazy
*/
class Lazy extends Abstract_Module {
/**
* Module slug.
*
* @var string
*/
protected $slug = 'lazy_load';
/**
* Lazy loading settings.
*
* @since 3.2.0
* @var array $settings
*/
private $options;
/**
* Page parser.
*
* @since 3.2.2
* @var Helpers\Parser $parser
*/
protected $parser;
/**
* Excluded classes list.
*
* @since 3.6.2
* @var array
*/
private $excluded_classes = array(
'no-lazyload', // Internal class to skip images.
'skip-lazy',
'rev-slidebg', // Skip Revolution slider images.
'soliloquy-preload', // Soliloquy slider.
);
/**
* Lazy constructor.
*
* @since 3.2.2
* @param Helpers\Parser $parser Page parser instance.
*/
public function __construct( Helpers\Parser $parser ) {
$this->parser = $parser;
parent::__construct();
}
/**
* Initialize module actions.
*
* @since 3.2.0
*/
public function init() {
// Only run on front end and if lazy loading is enabled.
if ( is_admin() || ! $this->is_active() ) {
return;
}
$this->options = $this->settings->get_setting( 'wp-smush-lazy_load' );
// Enabled without settings? Don't think so... Exit.
if ( ! $this->options ) {
return;
}
// Disable WordPress native lazy load.
add_filter( 'wp_lazy_loading_enabled', '__return_false' );
// Load js file that is required in public facing pages.
add_action( 'wp_head', array( $this, 'add_inline_styles' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ), 99 );
if ( defined( 'WP_SMUSH_ASYNC_LAZY' ) && WP_SMUSH_ASYNC_LAZY ) {
add_filter( 'script_loader_tag', array( $this, 'async_load' ), 10, 2 );
}
// Allow lazy load attributes in img tag.
add_filter( 'wp_kses_allowed_html', array( $this, 'add_lazy_load_attributes' ) );
$this->parser->enable( $this->slug );
if ( isset( $this->options['format']['iframe'] ) && $this->options['format']['iframe'] ) {
$this->parser->enable( 'iframes' );
}
add_filter( 'wp_smush_should_skip_parse', array( $this, 'maybe_skip_parse' ) );
// Filter images.
if ( ! isset( $this->options['output']['content'] ) || ! $this->options['output']['content'] ) {
add_filter( 'the_content', array( $this, 'exclude_from_lazy_loading' ), 100 );
}
if ( ! isset( $this->options['output']['thumbnails'] ) || ! $this->options['output']['thumbnails'] ) {
add_filter( 'post_thumbnail_html', array( $this, 'exclude_from_lazy_loading' ), 100 );
}
if ( ! isset( $this->options['output']['gravatars'] ) || ! $this->options['output']['gravatars'] ) {
add_filter( 'get_avatar', array( $this, 'exclude_from_lazy_loading' ), 100 );
}
if ( ! isset( $this->options['output']['widgets'] ) || ! $this->options['output']['widgets'] ) {
add_action( 'dynamic_sidebar_before', array( $this, 'filter_sidebar_content_start' ), 0 );
add_action( 'dynamic_sidebar_after', array( $this, 'filter_sidebar_content_end' ), 1000 );
}
}
/**
* Add inline styles at the top of the page for pre-loaders and effects.
*
* @since 3.2.0
*/
public function add_inline_styles() {
if ( $this->is_amp() ) {
return;
}
// Fix for poorly coded themes that do not remove the no-js in the HTML class.
?>
<script>
document.documentElement.className = document.documentElement.className.replace( 'no-js', 'js' );
</script>
<?php
if ( ! $this->options['animation']['selected'] || 'none' === $this->options['animation']['selected'] ) {
return;
}
// Spinner.
if ( 'spinner' === $this->options['animation']['selected'] ) {
$loader = WP_SMUSH_URL . 'app/assets/images/smush-lazyloader-' . $this->options['animation']['spinner']['selected'] . '.gif';
if ( isset( $this->options['animation']['spinner']['selected'] ) && 5 < (int) $this->options['animation']['spinner']['selected'] ) {
$loader = wp_get_attachment_image_src( $this->options['animation']['spinner']['selected'], 'full' );
$loader = $loader[0];
}
$background = 'rgba(255, 255, 255, 0)';
} else {
// Placeholder.
$loader = WP_SMUSH_URL . 'app/assets/images/smush-placeholder.png';
$background = '#FAFAFA';
if ( isset( $this->options['animation']['placeholder']['selected'] ) && 2 === (int) $this->options['animation']['placeholder']['selected'] ) {
$background = '#333333';
}
if ( isset( $this->options['animation']['placeholder']['selected'] ) && 2 < (int) $this->options['animation']['placeholder']['selected'] ) {
$loader = wp_get_attachment_image_src( (int) $this->options['animation']['placeholder']['selected'], 'full' );
// Can't find a loader on multisite? Try main site.
if ( ! $loader && is_multisite() ) {
switch_to_blog( 1 );
$loader = wp_get_attachment_image_src( (int) $this->options['animation']['placeholder']['selected'], 'full' );
restore_current_blog();
}
$loader = $loader[0];
}
if ( isset( $this->options['animation']['placeholder']['color'] ) ) {
$background = $this->options['animation']['placeholder']['color'];
}
}
// Fade in.
$fadein = isset( $this->options['animation']['fadein']['duration'] ) ? $this->options['animation']['fadein']['duration'] : 0;
$delay = isset( $this->options['animation']['fadein']['delay'] ) ? $this->options['animation']['fadein']['delay'] : 0;
?>
<style>
.no-js img.lazyload { display: none; }
figure.wp-block-image img.lazyloading { min-width: 150px; }
<?php if ( 'fadein' === $this->options['animation']['selected'] ) : ?>
.lazyload, .lazyloading { opacity: 0; }
.lazyloaded {
opacity: 1;
transition: opacity <?php echo esc_html( $fadein ); ?>ms;
transition-delay: <?php echo esc_html( $delay ); ?>ms;
}
<?php else : ?>
.lazyload { opacity: 0; }
.lazyloading {
border: 0 !important;
opacity: 1;
background: <?php echo esc_attr( $background ); ?> url('<?php echo esc_url( $loader ); ?>') no-repeat center !important;
background-size: 16px auto !important;
min-width: 16px;
}
<?php endif; ?>
</style>
<?php
}
/**
* Enqueue JS files required in public pages.
*
* @since 3.2.0
*/
public function enqueue_assets() {
if ( $this->is_amp() ) {
return;
}
$script = WP_SMUSH_URL . 'app/assets/js/smush-lazy-load.min.js';
// Native lazy loading support.
if ( isset( $this->options['native'] ) && $this->options['native'] ) {
$script = WP_SMUSH_URL . 'app/assets/js/smush-lazy-load-native.min.js';
}
$in_footer = isset( $this->options['footer'] ) ? $this->options['footer'] : true;
wp_enqueue_script(
'smush-lazy-load',
$script,
array(),
WP_SMUSH_VERSION,
$in_footer
);
$this->add_masonry_support();
if ( defined( 'WP_SMUSH_LAZY_LOAD_AVADA' ) && WP_SMUSH_LAZY_LOAD_AVADA ) {
$this->add_avada_support();
}
$this->add_divi_support();
$this->add_soliloquy_support();
}
/**
* Async load the lazy load scripts.
*
* @since 3.7.0
*
* @param string $tag The <script> tag for the enqueued script.
* @param string $handle The script's registered handle.
*
* @return string
*/
public function async_load( $tag, $handle ) {
if ( 'smush-lazy-load' === $handle ) {
return str_replace( ' src', ' async="async" src', $tag );
}
return $tag;
}
/**
* Add support for plugins that use the masonry grid system (Block Gallery and CoBlocks plugins).
*
* @since 3.5.0
*
* @see https://wordpress.org/plugins/coblocks/
* @see https://github.com/godaddy/block-gallery
* @see https://masonry.desandro.com/methods.html#layout-masonry
*/
private function add_masonry_support() {
if ( ! function_exists( 'has_block' ) ) {
return;
}
// None of the supported blocks are active - exit.
if ( ! has_block( 'blockgallery/masonry' ) && ! has_block( 'coblocks/gallery-masonry' ) ) {
return;
}
$js = "var e = jQuery( '.wp-block-coblocks-gallery-masonry ul' );";
if ( has_block( 'blockgallery/masonry' ) ) {
$js = "var e = jQuery( '.wp-block-blockgallery-masonry ul' );";
}
$block_gallery_compat = "jQuery(document).on('lazyloaded', function(){{$js} if ('function' === typeof e.masonry) e.masonry();});";
wp_add_inline_script( 'smush-lazy-load', $block_gallery_compat );
}
/**
* Add fusion gallery support in Avada theme.
*
* @since 3.7.0
*/
private function add_avada_support() {
if ( ! defined( 'FUSION_BUILDER_VERSION' ) ) {
return;
}
$js = "var e = jQuery( '.fusion-gallery' );";
$block_gallery_compat = "jQuery(document).on('lazyloaded', function(){{$js} if ('function' === typeof e.isotope) e.isotope();});";
wp_add_inline_script( 'smush-lazy-load', $block_gallery_compat );
}
/**
* Adds lazyload support to Divi & it's Waypoint library.
*
* @since 3.9.0
*/
private function add_divi_support() {
if ( ! defined( 'ET_BUILDER_THEME' ) || ! ET_BUILDER_THEME ) {
return;
}
$script = "function rw() { Waypoint.refreshAll(); } window.addEventListener( 'lazybeforeunveil', rw, false); window.addEventListener( 'lazyloaded', rw, false);";
wp_add_inline_script( 'smush-lazy-load', $script );
}
/**
* Prevents the navigation from being missaligned in Soliloquy when lazy loading.
*
* @since 3.7.0
*/
private function add_soliloquy_support() {
if ( ! function_exists( 'soliloquy' ) ) {
return;
}
$js = "var e = jQuery( '.soliloquy-image:not(.lazyloaded)' );";
$soliloquy = "jQuery(document).on('lazybeforeunveil', function(){{$js}e.each(function(){lazySizes.loader.unveil(this);});});";
wp_add_inline_script( 'smush-lazy-load', $soliloquy );
}
/**
* Make sure WordPress does not filter out img elements with lazy load attributes.
*
* @since 3.2.0
*
* @param array $allowedposttags Allowed post tags.
*
* @return mixed
*/
public function add_lazy_load_attributes( $allowedposttags ) {
if ( ! isset( $allowedposttags['img'] ) ) {
return $allowedposttags;
}
$smush_attributes = array(
'data-src' => true,
'data-srcset' => true,
'data-sizes' => true,
);
$img_attributes = array_merge( $allowedposttags['img'], $smush_attributes );
$allowedposttags['img'] = $img_attributes;
return $allowedposttags;
}
/**
* Check if we need to skip parsing of this page.
*
* @since 3.2.2
* @param bool $skip Skip parsing.
*
* @return bool
*/
public function maybe_skip_parse( $skip ) {
// Don't lazy load for feeds, previews, embeds.
if ( is_feed() || is_preview() || is_embed() ) {
$skip = true;
}
if ( $this->skip_post_type() || $this->is_exluded_uri() ) {
$skip = true;
}
return $skip;
}
/**
* Parse image for Lazy load.
*
* @since 3.2.2
*
* @param string $src Image URL.
* @param string $image Image tag (<img>).
* @param string $type Element type. Accepts: 'img', 'source' or 'iframe'. Default: 'img'.
*
* @return string
*/
public function parse_image( $src, $image, $type = 'img' ) {
if ( $this->is_amp() ) {
return $image;
}
/**
* Filter to skip a single image from lazy load.
*
* @since 3.3.0 Added $image param.
*
* @param bool $skip Should skip? Default: false.
* @param string $src Image url.
* @param string $image Image.
*/
if ( apply_filters( 'smush_skip_image_from_lazy_load', false, $src, $image ) ) {
return $image;
}
$is_gravatar = false !== strpos( $src, 'gravatar.com' );
$path = wp_parse_url( $src, PHP_URL_PATH );
// Make sure $path is not null, because passing null to parameter is deprecated in PHP 8.1.
if ( empty( $path ) ) {
return $image;
}
$ext = strtolower( pathinfo( $path, PATHINFO_EXTENSION ) );
$ext = 'jpg' === $ext ? 'jpeg' : $ext;
// If not a supported image in src or not an iframe - skip.
$iframe = 'iframe' === substr( $image, 1, 6 );
if ( ! $is_gravatar && ! in_array( $ext, array( 'jpeg', 'gif', 'png', 'svg', 'webp' ), true ) && ! $iframe ) {
return $image;
}
// Check if some image formats are excluded.
if ( in_array( false, $this->options['format'], true ) && isset( $this->options['format'][ $ext ] ) && ! $this->options['format'][ $ext ] ) {
return $image;
}
// Check if iframes are excluded.
if ( $iframe && isset( $this->options['format']['iframe'] ) && ! $this->options['format']['iframe'] ) {
return $image;
}
/**
* Filter to skip a iframe from lazy load.
*
* @since 3.4.2
* @since 3.7.0 Added filtering by empty source. Better approach to make the get_images_from_content() work
* by finding all the images (even escaped). But it does what it does.
*
* @param bool $skip Should skip? Default: false.
* @param string $src Iframe url.
*/
if ( empty( $src ) || ( $iframe && apply_filters( 'smush_skip_iframe_from_lazy_load', false, $src ) ) ) {
return $image;
}
// Check if the iframe URL is valid if not skip it from lazy load.
if ( $iframe && esc_url_raw( $src ) !== $src ) {
return $image;
}
if ( $this->has_excluded_class_or_id( $image ) ) {
return $image;
}
// Check for the data-skip-lazy attribute.
if ( false !== strpos( $image, 'data-skip-lazy' ) ) {
return $image;
}
$new_image = $image;
/**
* The sizes attribute does not have to be replaced to data-sizes, but it fixes the W3C validation.
*
* @since 3.6.2
*/
$attributes = array( 'src', 'sizes' );
foreach ( $attributes as $attribute ) {
$attr = Helpers\Parser::get_attribute( $new_image, $attribute );
if ( $attr ) {
Helpers\Parser::remove_attribute( $new_image, $attribute );
Helpers\Parser::add_attribute( $new_image, "data-{$attribute}", $attr );
}
}
// Change srcset to data-srcset attribute.
$new_image = preg_replace( '/<(.*?)(srcset=)(.*?)>/i', '<$1data-$2$3>', $new_image );
// Exit early if this is a <source> element from <picture>.
if ( 'source' === $type ) {
return $new_image;
}
// Add .lazyload class.
$class = Helpers\Parser::get_attribute( $new_image, 'class' );
if ( $class ) {
$class .= ' lazyload';
} else {
$class = 'lazyload';
}
Helpers\Parser::remove_attribute( $new_image, 'class' );
Helpers\Parser::add_attribute( $new_image, 'class', apply_filters( 'wp_smush_lazy_load_classes', $class ) );
Helpers\Parser::add_attribute( $new_image, 'src', 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' );
// Use noscript element in HTML to load elements normally when JavaScript is disabled in browser.
if ( ! $iframe && ( ! isset( $this->options['noscript'] ) || ! $this->options['noscript'] ) ) {
$new_image .= '<noscript>' . $image . '</noscript>';
}
return $new_image;
}
/**
* Get images from content and add exclusion class.
*
* @since 3.2.2
*
* @param string $content Page/block content.
*
* @return string
*/
public function exclude_from_lazy_loading( $content ) {
$images = $this->parser->get_images_from_content( $content );
if ( empty( $images ) ) {
return $content;
}
foreach ( $images[0] as $key => $image ) {
$new_image = $image;
// Add .no-lazyload class.
$class = Helpers\Parser::get_attribute( $new_image, 'class' );
if ( $class ) {
Helpers\Parser::remove_attribute( $new_image, 'class' );
$class .= ' no-lazyload';
} else {
$class = 'no-lazyload';
}
Helpers\Parser::add_attribute( $new_image, 'class', $class );
/**
* Filters the no-lazyload image.
*
* @since 3.8.5
*
* @param string $text The image that can be filtered.
*/
$new_image = apply_filters( 'wp_smush_filter_no_lazyload_image', $new_image );
$content = str_replace( $image, $new_image, $content );
}
return $content;
}
/**
* Check if this is part of the allowed post type.
*
* @since 3.2.0
*
* @return bool
*/
private function skip_post_type() {
// If not settings are set, probably, all are disabled.
if ( ! is_array( $this->options['include'] ) ) {
return true;
}
$blog_is_frontpage = ( 'posts' === get_option( 'show_on_front' ) && ! is_multisite() ) ? true : false;
if ( is_front_page() && isset( $this->options['include']['frontpage'] ) && ! $this->options['include']['frontpage'] ) {
return true;
} elseif ( is_home() && isset( $this->options['include']['home'] ) && ! $this->options['include']['home'] && ! $blog_is_frontpage ) {
return true;
} elseif ( is_page() && isset( $this->options['include']['page'] ) && ! $this->options['include']['page'] ) {
return true;
} elseif ( is_single() && isset( $this->options['include']['single'] ) && ! $this->options['include']['single'] ) {
return true;
} elseif ( is_archive() && isset( $this->options['include']['archive'] ) && ! $this->options['include']['archive'] ) {
return true;
} elseif ( is_category() && isset( $this->options['include']['category'] ) && ! $this->options['include']['category'] ) {
return true;
} elseif ( is_tag() && isset( $this->options['include']['tag'] ) && ! $this->options['include']['tag'] ) {
return true;
} elseif ( self::skip_custom_post_type( get_post_type() ) ) {
return true;
}
return false;
}
/**
* Skip custom post type added in settings.
*
* @since 3.5.0
*
* @param string $post_type Post type to check in settings.
*
* @return bool
*/
private function skip_custom_post_type( $post_type ) {
if ( isset( $this->options['include'][ $post_type ] ) && ! $this->options['include'][ $post_type ] ) {
return true;
}
return false;
}
/**
* Check if the page has been added to Post, Pages & URLs filter in lazy loading settings.
*
* @since 3.2.0
*
* @return bool
*/
private function is_exluded_uri() {
// No exclusion rules defined.
if ( ! isset( $this->options['exclude-pages'] ) || empty( $this->options['exclude-pages'] ) ) {
return false;
}
$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
// Remove empty values.
$uri_pattern = array_filter( $this->options['exclude-pages'] );
$uri_pattern = implode( '|', $uri_pattern );
if ( preg_match( "#{$uri_pattern}#i", $request_uri ) ) {
return true;
}
return false;
}
/**
* Check if the image has a defined class or ID.
*
* @since 3.2.0
*
* @param string $image Image.
*
* @return bool
*/
private function has_excluded_class_or_id( $image ) {
$image_classes = Helpers\Parser::get_attribute( $image, 'class' );
$image_classes = explode( ' ', $image_classes );
$image_id = '#' . Helpers\Parser::get_attribute( $image, 'id' );
if ( in_array( $image_id, $this->options['exclude-classes'], true ) ) {
return true;
}
foreach ( $image_classes as $class ) {
if ( in_array( $class, $this->excluded_classes, true ) ) {
return true;
}
if ( in_array( ".{$class}", $this->options['exclude-classes'], true ) ) {
return true;
}
}
return false;
}
/**
* Buffer sidebar content.
*
* @since 3.2.0
*/
public function filter_sidebar_content_start() {
ob_start();
}
/**
* Process buffered content.
*
* @since 3.2.0
*/
public function filter_sidebar_content_end() {
$content = ob_get_clean();
echo $this->exclude_from_lazy_loading( $content );
unset( $content );
}
/**
* Determine whether it is an AMP page.
*
* @since 3.4.0
*
* @return bool Whether AMP.
*/
private function is_amp() {
return function_exists( 'is_amp_endpoint' ) && is_amp_endpoint();
}
}