Skip to content

Commit

Permalink
feat: add font-loading class (#2418)
Browse files Browse the repository at this point in the history
  • Loading branch information
adekbadek authored Feb 7, 2025
1 parent 09897b0 commit 24888a3
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
16 changes: 16 additions & 0 deletions newspack-theme/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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' );

Expand Down
5 changes: 5 additions & 0 deletions newspack-theme/inc/template-functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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' );
Expand Down
8 changes: 8 additions & 0 deletions newspack-theme/js/src/font-loading.js
Original file line number Diff line number Diff line change
@@ -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');
}
});

0 comments on commit 24888a3

Please sign in to comment.