| 1 |
<?php |
| 2 |
namespace Falcon; |
| 3 |
|
| 4 |
use _WP_Dependency; |
| 5 |
|
| 6 |
class LazyLoadCSS { |
| 7 |
public function __construct() { |
| 8 |
add_action( 'wp_enqueue_scripts', [ $this, 'process' ], PHP_INT_MAX ); |
| 9 |
add_action( 'wp_footer', [ $this, 'process' ], 15 ); // WordPress prints footer scripts at priority 20, so we must run before that. |
| 10 |
} |
| 11 |
|
| 12 |
public function process() { |
| 13 |
$files = $this->get_files(); |
| 14 |
|
| 15 |
foreach ( $files as $file ) { |
| 16 |
$this->lazy_load( $file ); |
| 17 |
} |
| 18 |
|
| 19 |
echo "\n"; |
| 20 |
} |
| 21 |
|
| 22 |
private function lazy_load( string $file ): void { |
| 23 |
$css = $this->get_css( $file ); |
| 24 |
if ( ! $css || ! wp_style_is( $css->handle, 'enqueued' ) ) { |
| 25 |
return; |
| 26 |
} |
| 27 |
|
| 28 |
wp_dequeue_style( $css->handle ); |
| 29 |
|
| 30 |
$url = add_query_arg( 'ver', $css->ver, $css->src ); |
| 31 |
// phpcs:ignore |
| 32 |
echo "\n", '<link rel="stylesheet" href="', esc_url( $url ) . '" media="print" onload="this.media=\'all\'">'; |
| 33 |
} |
| 34 |
|
| 35 |
private function get_css( string $file ): ?_WP_Dependency { |
| 36 |
$wp_styles = wp_styles(); |
| 37 |
|
| 38 |
foreach ( $wp_styles->registered as $handle => $registered ) { |
| 39 |
if ( $handle === $file || str_contains( $registered->src, $file ) ) { |
| 40 |
return $registered; |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
return null; |
| 45 |
} |
| 46 |
|
| 47 |
private function get_files(): array { |
| 48 |
$option = get_option( 'falcon', [] ); |
| 49 |
$files = $option['lazy_load_css'] ?? ''; |
| 50 |
$files = array_map( 'trim', explode( "\n", $files ) ); |
| 51 |
|
| 52 |
return $files; |
| 53 |
} |
| 54 |
} |
| 55 |
|