Customizer – How to live update @font-face?

I am using customizer to select from my own hosted fonts, and it works pretty well. The only thing I can’t figure out is how to use postMessage for the live preview. Here’s what I currently have:

Customizer control / setting

<?php
function site_title_font( $controls ) {

$controls[] = array(
'priority' => 1,
'type' => 'select',
'setting' => 'site_title_font',
'label' => __( 'Site Title Font', 'alphatest' ),
'section' => 'site_title_font_section',
'transport' => 'postMessage',
'default' => 'default',
'choices' => include (get_template_directory() . '/customizer/fonts/groovy-fonts.txt')
);

return $controls;
}
add_filter( 'kirki/controls', 'site_title_font' );
?>

fontface.php ouputs the css

<?php
if ( get_theme_mod( site_title_font ) ) {
echo'@font-face {
font-family: ' . get_theme_mod( site_title_font ) . ';
src: url('/media/fonts2/' . get_theme_mod( site_title_font ) . '/webfont.woff2') format('woff2'),
url('/media/fonts2/' . get_theme_mod( site_title_font ) . '/webfont.woff') format('woff');
}';
}
?>

JavaScript:

( function( $ ) {
wp.customize( 'site_title_font', function( value ) {
value.bind( function( to ) {
$( 'font-family' ).css( to );
} );
} );
} )( jQuery );

Output after saving

<style>
@font-face {
font-family: a780-deco-regular;
src: url('/media/fonts2/a780-deco-regular/webfont.woff2') format('woff2'),
url('/media/fonts2/a780-deco-regular/webfont.woff') format('woff');
}

h1.site-title,
p.site-title a {
font-family: a780-deco-regular;
font-weight: 300;
}
</style>

Please note that the css is “after” saving. If I remove ‘transport’ => ‘postMessage’ from the customize setting, everything works fine but the page has to refresh with each font change — and I have a LOT of fonts :slight_smile: . I just can’t figure out how to get the JavaScript to work. I think the issue is having to update both @font-face and the .site-title css at the same time. Any ideas?

Thanks