| 1 |
<?php |
| 2 |
/** |
| 3 |
* Speculative Loading |
| 4 |
* |
| 5 |
* Injects a <script type="speculationrules"> block to enable browser-native |
| 6 |
* speculative prefetch / prerender of same-origin links. |
| 7 |
* |
| 8 |
* @package Upress\EzCache |
| 9 |
*/ |
| 10 |
namespace Upress\EzCache; |
| 11 |
|
| 12 |
class SpeculativeLoading { |
| 13 |
|
| 14 |
private static $instance; |
| 15 |
private $settings; |
| 16 |
|
| 17 |
private function __construct() { |
| 18 |
$this->settings = Settings::get_settings(); |
| 19 |
} |
| 20 |
|
| 21 |
public static function instance() { |
| 22 |
if ( ! self::$instance ) { |
| 23 |
self::$instance = new self(); |
| 24 |
} |
| 25 |
return self::$instance; |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Register WordPress hooks. |
| 30 |
*/ |
| 31 |
public function register() { |
| 32 |
if ( empty( $this->settings->enable_speculative_loading ) ) { |
| 33 |
return; |
| 34 |
} |
| 35 |
add_action( 'wp_head', [ $this, 'inject_speculation_rules' ], 2 ); |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Print the speculationrules script tag. |
| 40 |
*/ |
| 41 |
public function inject_speculation_rules() { |
| 42 |
if ( is_admin() ) { return; } |
| 43 |
|
| 44 |
$mode = isset( $this->settings->speculative_mode ) ? $this->settings->speculative_mode : 'moderate'; |
| 45 |
$rules = $this->build_rules( $mode ); |
| 46 |
echo '<script type="speculationrules">' . wp_json_encode( $rules ) . '</script>' . "\n"; |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Build the speculation rules JSON object. |
| 51 |
* |
| 52 |
* @param string $mode conservative | moderate | eager |
| 53 |
* @return array |
| 54 |
*/ |
| 55 |
private function build_rules( $mode ) { |
| 56 |
switch ( $mode ) { |
| 57 |
case 'eager': |
| 58 |
// Prerender all same-origin links eagerly |
| 59 |
return [ |
| 60 |
'prerender' => [ |
| 61 |
[ |
| 62 |
'where' => [ 'href_matches' => '/*' ], |
| 63 |
'eagerness' => 'eager', |
| 64 |
], |
| 65 |
], |
| 66 |
]; |
| 67 |
|
| 68 |
case 'conservative': |
| 69 |
// Only prefetch same-origin links user hovers on |
| 70 |
return [ |
| 71 |
'prefetch' => [ |
| 72 |
[ |
| 73 |
'where' => [ |
| 74 |
'and' => [ |
| 75 |
[ 'href_matches' => '/*' ], |
| 76 |
[ 'not' => [ 'selector_matches' => '.no-prefetch' ] ], |
| 77 |
], |
| 78 |
], |
| 79 |
'eagerness' => 'conservative', |
| 80 |
], |
| 81 |
], |
| 82 |
]; |
| 83 |
|
| 84 |
case 'moderate': |
| 85 |
default: |
| 86 |
// Prerender likely navigations (moderate eagerness) |
| 87 |
return [ |
| 88 |
'prerender' => [ |
| 89 |
[ |
| 90 |
'where' => [ |
| 91 |
'and' => [ |
| 92 |
[ 'href_matches' => '/*' ], |
| 93 |
[ 'not' => [ 'selector_matches' => '[rel~=nofollow]' ] ], |
| 94 |
[ 'not' => [ 'href_matches' => '/wp-admin/*' ] ], |
| 95 |
[ 'not' => [ 'href_matches' => '/wp-login.php' ] ], |
| 96 |
], |
| 97 |
], |
| 98 |
'eagerness' => 'moderate', |
| 99 |
], |
| 100 |
], |
| 101 |
]; |
| 102 |
} |
| 103 |
} |
| 104 |
} |
| 105 |
|