From c5b69b7acc589d3a3ba6bd82888707a66f2c9b84 Mon Sep 17 00:00:00 2001 From: Adam Cassis Date: Fri, 29 Nov 2024 10:08:40 +0100 Subject: [PATCH] feat: add font-loading class --- newspack-theme/functions.php | 16 ++++++++++++++++ newspack-theme/inc/template-functions.php | 5 +++++ newspack-theme/js/src/font-loading.js | 8 ++++++++ 3 files changed, 29 insertions(+) create mode 100644 newspack-theme/js/src/font-loading.js diff --git a/newspack-theme/functions.php b/newspack-theme/functions.php index 8701e3b3c..0d82f1cce 100755 --- a/newspack-theme/functions.php +++ b/newspack-theme/functions.php @@ -423,6 +423,13 @@ function newspack_content_width() { } add_action( 'template_redirect', 'newspack_content_width', 0 ); +/** + * Return the list of custom fonts in use. + */ +function newspack_get_used_custom_fonts(): array { + return array_filter( [ get_theme_mod( 'font_header', '' ), get_theme_mod( 'font_body', '' ) ] ); +} + /** * Enqueue scripts and styles. */ @@ -486,6 +493,15 @@ function newspack_scripts() { wp_enqueue_script( 'amp-animation', 'https://cdn.ampproject.org/v0/amp-animation-0.1.js', array(), '0.1', true ); wp_enqueue_script( 'amp-position-observer', 'https://cdn.ampproject.org/v0/amp-position-observer-0.1.js', array(), '0.1', true ); } + + wp_enqueue_script( 'newspack-font-loading', get_theme_file_uri( '/js/dist/font-loading.js' ), array(), wp_get_theme()->get( 'Version' ), true ); + wp_localize_script( + 'newspack-font-loading', + 'newspackFontLoading', + [ + 'fonts' => newspack_get_used_custom_fonts(), + ] + ); } add_action( 'wp_enqueue_scripts', 'newspack_scripts' ); diff --git a/newspack-theme/inc/template-functions.php b/newspack-theme/inc/template-functions.php index 210cedbc7..955a8988d 100755 --- a/newspack-theme/inc/template-functions.php +++ b/newspack-theme/inc/template-functions.php @@ -258,6 +258,11 @@ function newspack_body_classes( $classes ) { $classes[] = 'fw-stacked'; } + // If custom fonts are used, add a class indicating that fonts will be loaded. The class will be removed by JS. + if ( ! empty( newspack_get_used_custom_fonts() ) ) { + $classes[] = 'newspack--font-loading'; + } + return $classes; } add_filter( 'body_class', 'newspack_body_classes' ); diff --git a/newspack-theme/js/src/font-loading.js b/newspack-theme/js/src/font-loading.js new file mode 100644 index 000000000..5d70e0193 --- /dev/null +++ b/newspack-theme/js/src/font-loading.js @@ -0,0 +1,8 @@ +const fontsToLoad = window.newspackFontLoading?.fonts || []; +Promise.all( + fontsToLoad.map(fontName => document.fonts.load(`1rem ${fontName}`)) +).then(res => { + if (res.length === fontsToLoad.length) { + document.body.classList.remove('newspack--font-loading'); + } +});