Skip to content

Commit 2c8c52f

Browse files
committed
add preloadFonts function to Front controller
1 parent 24c33c0 commit 2c8c52f

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/Base/Hooks.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ public static function initHooks(): void
9191
add_action('wp_enqueue_scripts', [Handlers\Front::class, 'loadFrontendJsData']);
9292
add_action('style_loader_src', [Handlers\Front::class, 'addFileTimeVerToStyles'], 20, 2);
9393
add_action('send_headers', [Handlers\Front::class, 'addNoCacheHeaders']);
94+
// Preload critical fonts to avoid layout shift on load
95+
add_action('wp_head', [Handlers\Front::class, 'preloadFonts'], 0);
9496
// Change excerpt dots
9597
add_filter('excerpt_more', [Handlers\Front::class, 'changeExcerptMore']);
9698
// Add GTM code

src/Handlers/Front.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,32 @@
1818
*/
1919
class Front
2020
{
21+
/**
22+
* Preload critical webfonts to reduce FOIT/FOUT and layout shift
23+
*
24+
* @return void
25+
*/
26+
public static function preloadFonts(): void
27+
{
28+
// Only run on the frontend and not in admin or feed requests
29+
if (is_admin() || is_feed() || is_robots()) {
30+
return;
31+
}
32+
33+
$fonts = [
34+
'fonts/roboto/roboto-v30-latin-regular.woff2',
35+
'fonts/roboto/roboto-v30-latin-500.woff2',
36+
];
37+
38+
foreach ($fonts as $relativePath) {
39+
$href = SK_ASSETS_URI . $relativePath;
40+
$path = SK_ASSETS_DIR . $relativePath;
41+
$ver = file_exists($path) ? filemtime($path) : null;
42+
$hrefWithVer = $ver ? add_query_arg('ver', $ver, $href) : $href;
43+
echo '<link rel="preload" href="' . esc_url($hrefWithVer) . '" as="font" type="font/woff2" crossorigin="anonymous">' . "\n";
44+
}
45+
}
46+
2147
/**
2248
* Load critical assets before blocks assets
2349
*

0 commit comments

Comments
 (0)