This repository has been archived by the owner on May 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPreload.php
86 lines (55 loc) · 1.55 KB
/
Preload.php
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
<?php
/**
* Helper for preloading resources
*
* @package ThemePlate
* @since 0.1.0
*/
namespace ThemePlate;
class Preload {
private static $storage = array();
public static function init() {
$resources = apply_filters( 'themeplate_preload_resources', array() );
foreach ( $resources as $resource ) {
self::insert( $resource );
}
$dependencies = apply_filters( 'themeplate_preload_dependencies', array() );
self::prepare();
self::process( $dependencies );
}
private static function prepare() {
global $wp_scripts, $wp_styles;
foreach ( array( $wp_scripts, $wp_styles ) as $dependencies ) {
if ( empty( $dependencies->queue ) || empty( $dependencies->registered ) ) {
continue;
}
$type = get_class( $dependencies );
self::$storage[ strtolower( substr( $type, 3, -1 ) ) ] = $dependencies->registered;
}
}
private static function process( $handles ) {
foreach ( self::$storage as $type => $dependencies ) {
foreach ( array_intersect( $handles, array_keys( $dependencies ) ) as $handle ) {
$item = array(
'href' => $dependencies[ $handle ]->src,
'as' => $type,
);
self::insert( $item );
}
}
}
private static function insert( $item ) {
$item = array( 'rel' => 'preload' ) + $item;
$html = '';
foreach ( $item as $attr => $value ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
if ( ! is_string( $attr ) ) {
$html .= " $value";
} else {
$html .= " $attr='$value'";
}
}
$html = trim( $html );
echo "<link $html />\n";
}
}