From a6e21f55ea869b87f5947131537ec2337ec30ff5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABl=20Robin?= Date: Fri, 15 Nov 2024 09:15:39 +0100 Subject: [PATCH] Closes #7066: 3.18 - Preconnect and prefetch removal (#7101) Co-authored-by: Michael Lee --- .../Media/Fonts/Frontend/Controller.php | 31 +++++++++++++++++++ .../Frontend/Controller/HTML/input_v1.php | 2 ++ .../Frontend/Controller/HTML/input_v1_v2.php | 2 ++ .../Frontend/Controller/HTML/input_v2.php | 2 ++ 4 files changed, 37 insertions(+) diff --git a/inc/Engine/Media/Fonts/Frontend/Controller.php b/inc/Engine/Media/Fonts/Frontend/Controller.php index 82bdc47644..b4a4ef7ffe 100644 --- a/inc/Engine/Media/Fonts/Frontend/Controller.php +++ b/inc/Engine/Media/Fonts/Frontend/Controller.php @@ -63,6 +63,8 @@ public function rewrite_fonts( string $html ): string { $html = $this->replace_font( $font, $html ); } + $html = $this->remove_preconnect_and_prefetch( $html ); + return $html; } @@ -111,6 +113,35 @@ protected function get_optimized_markup( string $hash, string $original_url ): s ); } + /** + + * Removes preconnect and prefetch links for Google Fonts from the HTML content. + * + * @param string $html HTML content. + * + * @return string Modified HTML content without preconnect and prefetch links. + */ + private function remove_preconnect_and_prefetch( string $html ) { + /** + * Filters the removal of Google preconnect/prefetch links. + * + * @since 3.18 + * + * @param bool $enable_removal Enable or disable removal of Google preconnect/prefetch links. + */ + $remove_links = wpm_apply_filters_typed( 'boolean', 'rocket_remove_font_pre_links', true ); + + if ( ! $remove_links ) { + return $html; + } + + $pattern = '/]*)(?:rel=["\'](?:dns-prefetch|preconnect)["\'])(?:[^>]*)(?:href=["\'](?:https?:)?\/\/(?:fonts\.(?:googleapis|gstatic)\.com)["\'])(?:[^>]*)>/i'; + + $html = preg_replace( $pattern, '', $html ); + + return $html; + } + /** * Disables the preload of Google Fonts. * diff --git a/tests/Fixtures/inc/Engine/Media/Fonts/Frontend/Controller/HTML/input_v1.php b/tests/Fixtures/inc/Engine/Media/Fonts/Frontend/Controller/HTML/input_v1.php index e49961654e..8765447423 100644 --- a/tests/Fixtures/inc/Engine/Media/Fonts/Frontend/Controller/HTML/input_v1.php +++ b/tests/Fixtures/inc/Engine/Media/Fonts/Frontend/Controller/HTML/input_v1.php @@ -9,6 +9,8 @@ Google Font V1 Template + +