Last active
October 26, 2017 14:43
-
-
Save m-e-h/4182831f4c4f125a6c4ce239b15d065a to your computer and use it in GitHub Desktop.
WP FontFaceObserver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Better font loading. | |
| */ | |
| add_action( 'wp_enqueue_scripts', 'abe_font_scripts' ); | |
| add_action( 'wp_head', 'abe_display_font' ); | |
| /** | |
| * Enqueue scripts and styles. | |
| */ | |
| function abe_font_scripts() { | |
| wp_enqueue_style( 'abe_google_font', 'https://fonts.googleapis.com/css?family=Cormorant+Garamond:500,600,600i|Open+Sans:300,300i,400,400i,600,600i' ); | |
| wp_enqueue_script( 'font_face', get_theme_file_uri( 'js/vendors/fontfaceobserver.js' ), false, false, true ); | |
| wp_add_inline_script( 'font_face', get_font_load_script() ); | |
| } | |
| function get_font_load_script() { | |
| return " | |
| (function () { | |
| var titleBold = new FontFaceObserver('Cormorant Garamond', {weight: 600}); | |
| var bodyFont = new FontFaceObserver('Open Sans', {weight: 400}); | |
| var bodyItalic = new FontFaceObserver('Open Sans', {style: 'italic'}); | |
| var bodyLight = new FontFaceObserver('Open Sans', {weight: 300}); | |
| var bodyBold = new FontFaceObserver('Open Sans', {weight: 600}); | |
| Promise.all([ | |
| titleBold.load(), | |
| bodyFont.load(), | |
| bodyItalic.load(), | |
| bodyLight.load(), | |
| bodyBold.load() | |
| ]).then(function () { | |
| document.documentElement.classList.add('fonts-loaded'); | |
| sessionStorage.fontsLoaded = true; | |
| }).catch(function () { | |
| sessionStorage.fontsLoaded = false; | |
| }); | |
| }());"; | |
| } | |
| function abe_display_font() { | |
| ?> | |
| <script> | |
| (function () { | |
| if (sessionStorage.fontsLoaded) { | |
| document.documentElement.classList.add('fonts-loaded'); | |
| } | |
| }()); | |
| </script> | |
| <style type="text/css"> | |
| .u-text-display,.u-dropcap::first-letter { | |
| font-weight: normal; | |
| } | |
| .fonts-loaded body, .fonts-loaded .u-text-read { | |
| font-family: 'Open Sans', sans-serif; | |
| } | |
| .fonts-loaded .u-text-display,.fonts-loaded .u-dropcap::first-letter { | |
| font-family: "Cormorant Garamond", serif; | |
| font-weight: 600; | |
| } | |
| </style> | |
| <?php } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment