Skip to content

Commit

Permalink
Closes #7243: preload fonts frontend rockethead (PR #7320)
Browse files Browse the repository at this point in the history
Co-authored-by: WordPressFan <[email protected]>
  • Loading branch information
Miraeld and wordpressfan authored Feb 22, 2025
1 parent daa4504 commit a412b60
Show file tree
Hide file tree
Showing 10 changed files with 119 additions and 73 deletions.
11 changes: 11 additions & 0 deletions inc/Engine/Media/PreloadFonts/Context/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,15 @@ public function is_allowed( array $data = [] ): bool {

return wpm_apply_filters_typed( 'boolean', 'rocket_preload_fonts_optimization', (bool) $this->options->get( 'rocket_preload_fonts', 1 ) );
}

/**
* Determines if the page is mobile and separate cache for mobile files is enabled.
*
* @return bool
*/
public function is_mobile_allowed(): bool {
return $this->options->get( 'cache_mobile', 0 )
&& $this->options->get( 'do_caching_mobile_files', 0 )
&& wp_is_mobile();
}
}
110 changes: 48 additions & 62 deletions inc/Engine/Media/PreloadFonts/Frontend/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,13 @@
use WP_Rocket\Engine\Media\PreloadFonts\Database\Queries\PreloadFonts as PFQuery;
use WP_Rocket\Engine\Media\PreloadFonts\Context\Context;
use WP_Rocket\Engine\Optimization\UrlTrait;
use WP_Rocket\Engine\Support\CommentTrait;
use WP_Rocket\Engine\Common\Head\ElementTrait;

class Controller implements ControllerInterface {
use UrlTrait;
use CommentTrait;
use ElementTrait;

/**
* Options instance
Expand Down Expand Up @@ -55,13 +59,10 @@ public function __construct( Options_Data $options, PFQuery $query, Context $con
* @return string
*/
public function optimize( string $html, $row ): string {
if ( ! $row->has_preload_fonts() ) {
if ( ! $this->context->is_allowed() || ! $row->has_preload_fonts() ) {
return $html;
}

$html = $this->preload_fonts( $html, $row );

return $html;
return $this->add_meta_comment( 'auto_preload_fonts', $html );
}

/**
Expand All @@ -72,6 +73,10 @@ public function optimize( string $html, $row ): string {
* @return array
*/
public function add_custom_data( array $data ): array {
if ( ! $this->context->is_allowed() ) {
return $data;
}

$system_fonts = [
'serif',
'sans-serif',
Expand Down Expand Up @@ -121,45 +126,6 @@ public function add_custom_data( array $data ): array {
return $data;
}

/**
* Preload Fonts in HTML.
*
* @param string $html HTML content.
* @param object $row Corresponding DB row.
*
* @return string
*/
private function preload_fonts( string $html, $row ): string {
if ( 'completed' !== $row->status || empty( $row->fonts ) || '[]' === $row->fonts ) {
return $html;
}

if ( ! preg_match( '#</title\s*>#', $html, $matches ) ) {
return $html;
}
$title = $matches[0];

$preload = $title;

$fonts = json_decode( $row->fonts, true );

if ( empty( $fonts ) ) {
return $html;
}

foreach ( $fonts as $font ) {
$preload .= $this->preload_tag( $font );
}

$replace = preg_replace( '#' . $title . '#', $preload, $html, 1 );

if ( null === $replace ) {
return $html;
}

return $replace;
}

/**
* Checks if the font URL is from a third party.
*
Expand All @@ -180,26 +146,46 @@ private function is_third_party_font( string $font_url ): bool {
}

/**
* Generates the preload tag for a font.
*
* @param string $font Font URL.
* Adds the preload fonts to the head tag.
*
* @return string
* @param array $items added to the head.
* @return array Items to be added to the head.
*/
private function preload_tag( string $font ): string {
if ( ! $this->is_relative( $font ) ) {
$crossorigin = $this->is_third_party_font( $font ) ? ' crossorigin' : '';
$tag = sprintf(
'<link rel="preload" data-rocket-preload as="font" href="%s"%s>',
esc_url( $font ),
$crossorigin
);
} else {
$tag = sprintf(
'<link rel="preload" data-rocket-preload as="font" href="%s">',
$font
);
public function add_preload_fonts_in_head( $items ) {

Check warning on line 154 in inc/Engine/Media/PreloadFonts/Frontend/Controller.php

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

inc/Engine/Media/PreloadFonts/Frontend/Controller.php#L154

The method add_preload_fonts_in_head() has a Cyclomatic Complexity of 10. The configured cyclomatic complexity threshold is 10.
if ( ! $this->context->is_allowed() ) {
return $items;
}

global $wp;

$url = untrailingslashit( home_url( add_query_arg( [], $wp->request ) ) );
$is_mobile = $this->context->is_mobile_allowed();

$row = $this->query->get_row( $url, $is_mobile );
if ( empty( $row ) || 'completed' !== $row->status || empty( $row->fonts ) || '[]' === $row->fonts ) {
return $items;
}

$fonts = json_decode( $row->fonts, true );

if ( empty( $fonts ) ) {
return $items;
}
return $tag;

foreach ( $fonts as $font ) {
$item_args = [
// 'id' => 'preload-font-' . md5( $font ), // Unique ID based on font URL.
'href' => esc_url( $font ),
'as' => 'font',
];

if ( ! $this->is_relative( $font ) && $this->is_third_party_font( $font ) ) {
$item_args[2] = 'crossorigin';
}

$items[] = $this->preload_link( $item_args );
}

return $items;
}
}
31 changes: 30 additions & 1 deletion inc/Engine/Media/PreloadFonts/Frontend/Subscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,26 @@
namespace WP_Rocket\Engine\Media\PreloadFonts\Frontend;

use WP_Rocket\Event_Management\Subscriber_Interface;
use WP_Rocket\Engine\Media\PreloadFonts\Frontend\Controller as PreloadFonts;

class Subscriber implements Subscriber_Interface {

/**
* Preload Fonts controller instance.
*
* @var PreloadFonts
*/
private $preload_fonts;

/**
* Subscriber constructor.
*
* @param PreloadFonts $preload_fonts Preload Fonts controller instance.
*/
public function __construct( PreloadFonts $preload_fonts ) {
$this->preload_fonts = $preload_fonts;
}

/**
* Returns an array of events that this subscriber wants to listen to.
*
Expand All @@ -15,6 +32,18 @@ class Subscriber implements Subscriber_Interface {
* @return array
*/
public static function get_subscribed_events(): array {
return [];
return [
'rocket_head_items' => [ 'add_preload_fonts_in_head', 30 ],
];
}

/**
* Add preload fonts into head.
*
* @param array $items Head items.
* @return array
*/
public function add_preload_fonts_in_head( $items ) {
return $this->preload_fonts->add_preload_fonts_in_head( $items );
}
}
9 changes: 7 additions & 2 deletions inc/Engine/Media/PreloadFonts/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public function register(): void {
$this->getContainer()->add( 'preload_fonts_query', PreloadFontsQuery::class );
$this->getContainer()->add( 'preload_fonts_context', Context::class )
->addArgument( $options );
$this->getContainer()->add( 'preload_fonts_front_controller', FrontendController::class )
$this->getContainer()->addShared( 'preload_fonts_front_controller', FrontendController::class )
->addArguments(
[
$this->getContainer()->get( 'options' ),
Expand All @@ -73,7 +73,12 @@ public function register(): void {
]
);

$this->getContainer()->addShared( 'preload_fonts_frontend_subscriber', FrontendSubscriber::class );
$this->getContainer()->addShared( 'preload_fonts_frontend_subscriber', FrontendSubscriber::class )
->addArguments(
[
$this->getContainer()->get( 'preload_fonts_front_controller' ),
]
);

$this->getContainer()->addShared( 'preload_fonts_factory', Factory::class )
->addArguments(
Expand Down
9 changes: 9 additions & 0 deletions inc/Plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,15 @@ class Plugin {
*/
private $is_valid_key;

/**
* Instance of the Options.
*
* @since 3.6
*
* @var Options
*/
private $options_api;

Check warning on line 100 in inc/Plugin.php

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

inc/Plugin.php#L100

Avoid unused private fields such as '$options_api'.

/**
* Instance of the Options_Data.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<html>
<head>
<title>Test</title><link rel="preload" data-rocket-preload as="font" href="http://example.org/assets/fonts/font1.woff2"><link rel="preload" data-rocket-preload as="font" href="http://example.org/assets/fonts/font2.ttf">
<title>Test</title>
<link data-rocket-preload as="font" href="http://example.org/assets/fonts/font1.woff2" rel="preload">
<link data-rocket-preload as="font" href="http://example.org/assets/fonts/font2.ttf" rel="preload">
<link rel="stylesheet" href="http://example.org/assets/fonts/font1.woff2">
<link rel="stylesheet" href="http://example.org/assets/fonts/font2.ttf">
</head>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<html>
<head>
<title>Test</title><link rel="preload" data-rocket-preload as="font" href="http://external.domain/assets/fonts/font1.woff2" crossorigin><link rel="preload" data-rocket-preload as="font" href="http://example.org/assets/fonts/font2.ttf">
<title>Test</title>
<link crossorigin data-rocket-preload as="font" href="http://external.domain/assets/fonts/font1.woff2" rel="preload">
<link data-rocket-preload as="font" href="http://example.org/assets/fonts/font2.ttf" rel="preload">
<link rel="stylesheet" href="http://external.domain/assets/fonts/font1.woff2">
<link rel="stylesheet" href="http://example.org/assets/fonts/font2.ttf">
</head>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<html>
<head>
<title>Test</title><link rel="preload" data-rocket-preload as="font" href="/assets/fonts/font1.woff2"><link rel="preload" data-rocket-preload as="font" href="/assets/fonts/font2.ttf">
<title>Test</title>
<link data-rocket-preload as="font" href="/assets/fonts/font1.woff2" rel="preload">
<link data-rocket-preload as="font" href="/assets/fonts/font2.ttf" rel="preload">
<link rel="stylesheet" href="/assets/fonts/font1.woff2">
<link rel="stylesheet" href="/assets/fonts/font2.ttf">
</head>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@
],
],
'lrc' => $lrc,
'preload_fonts' => $preload_fonts_empty
'preload_fonts' => $preload_fonts_empty,
],
'expected' => $html_output_with_preload,
],
Expand All @@ -240,7 +240,7 @@
],
],
'lrc' => $lrc,
'preload_fonts' => $preload_fonts_empty
'preload_fonts' => $preload_fonts_empty,
],
'expected' => $html_output,
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function set_up() {

add_filter( 'rocket_disable_meta_generator', '__return_true' );

$this->unregisterAllCallbacksExcept( 'rocket_buffer', 'maybe_apply_optimizations', 17 );
$this->unregisterAllCallbacksExceptMulti('rocket_buffer', [17 => 'maybe_apply_optimizations', 100000 => 'insert_rocket_head']);
}

public function tear_down() {
Expand Down Expand Up @@ -97,8 +97,8 @@ public function testShouldReturnAsExpected( $config, $expected ) {
add_filter( 'pre_get_rocket_option_cache_logged_user', [ $this, 'get_cache_user' ] );

$this->assertSame(
trim($expected),
trim(apply_filters( 'rocket_buffer', $config['html'] ))
$this->format_the_html($expected),
$this->format_the_html(apply_filters( 'rocket_buffer', $config['html'] ))
);
}

Expand Down

0 comments on commit a412b60

Please sign in to comment.