Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add font-loading class #2418

Open
wants to merge 1 commit into
base: trunk
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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');
}
});