PluginProbe
Falcon – Cache, Performance, Security, Cleanup, and Tweaks / 2.9.2
Falcon – Cache, Performance, Security, Cleanup, and Tweaks v2.9.2
2.11.2 2.11.1 2.11.0 2.10.1 trunk 1.0.1 1.0.2 1.0.3 1.1 1.2 1.2.1 1.2.2 1.2.3 1.2.4 1.3.0 1.3.3 2.0.0 2.0.1 2.0.2 2.0.3 2.0.4 2.0.5 2.1.0 2.10.0 2.2.0 All 45 releases
falcon / src / LazyLoadCSS.php

LazyLoadCSS.php in Falcon – Cache, Performance, Security, Cleanup, and Tweaks 2.9.2, at src/LazyLoadCSS.php

55 lines 1.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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