-
Notifications
You must be signed in to change notification settings - Fork 0
/
preconnect-cleaner.php
60 lines (47 loc) · 1.65 KB
/
preconnect-cleaner.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
<?php
/**
* Plugin Name: Preconnect Cleaner
* Plugin URI: https://github.com/ItinerisLtd/preconnect-cleaner/
* Description: Preconnect Cleaner.
* Version: 0.2.0
* Author: Itineris Limited
* Author URI: https://www.itineris.co.uk/
* Text Domain: preconnect-cleaner
*/
declare(strict_types=1);
namespace Itineris\PreconnectCleaner;
use WP_Dependencies;
// If this file is called directly, abort.
if (! defined('WPINC')) {
die;
}
add_filter('wp_resource_hints', function (array $urls, string $relation_type): array {
$wp_scripts = $GLOBALS['wp_scripts'];
$wp_styles = $GLOBALS['wp_styles'];
$unique_urls = [];
foreach ([$wp_scripts, $wp_styles] as $dependencies) {
if ($dependencies instanceof WP_Dependencies && ! empty($dependencies->queue)) {
foreach ($dependencies->queue as $handle) {
if (!isset($dependencies->registered[$handle])) {
continue;
}
$dependency = $dependencies->registered[$handle];
$parsed = wp_parse_url($dependency->src);
if (
! empty($parsed['host'])
&& ! in_array($parsed['host'], $unique_urls, true)
&& $parsed['host'] !== $_SERVER['SERVER_NAME'] //phpcs:ignore
) {
$unique_urls[] = ($parsed['scheme'] ?? 'https') . '://' . $parsed['host'];
}
}
}
}
if ('dns-prefetch' === $relation_type) {
$urls = [];
}
if ('preconnect' === $relation_type) {
$urls = $unique_urls;
}
return $urls;
}, 0, 2);