Skip to content

Instantly share code, notes, and snippets.

@ylkyrg
Created July 5, 2020 16:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ylkyrg/d1957176ca984c2602ca975b1075f310 to your computer and use it in GitHub Desktop.
Save ylkyrg/d1957176ca984c2602ca975b1075f310 to your computer and use it in GitHub Desktop.
WordPress plugin to optimise google fonts.
<?php
/**
* Plugin Name: Optimise Google Fonts
* Description: Add optimisations for loading Google Fonts.
* Version: 0.1.0
* Author: Gary Kealy
* Author URI: https://garykealy.dev
* License: GNU General Public License v2 or later
*/
namespace ylkyrg;
class OptimiseGoogleFonts {
/**
* @var array
*/
protected $options;
public function __construct( $options = [] ) {
$this->options = $options;
}
public function run() {
add_filter( 'style_loader_tag', [ $this, 'async_css' ], 10, 3 );
add_action( 'wp_head', [ $this, 'preload' ], 1 );
add_filter( 'wp_resource_hints', [ $this, 'resource_hints' ], 10, 2 );
}
/**
* Load Google Fonts Asynchrously
*
* @see https://www.filamentgroup.com/lab/load-css-simpler/
*/
public function async_css( $html, $handle, $href ) {
if (
! empty( $this->options['handle'] ) &&
$handle !== $this->options['handle']
) {
return $html;
}
if ( false === strpos( $href, 'fonts.googleapis.com/css' ) ) {
return $html;
}
if ( false !== strpos( $html, "media='all'" ) ) {
return str_replace(
"media='all'",
"media='print' onload=\"this.media='all'\"",
$html
);
}
return str_replace(
"rel='stylesheet'",
"rel='stylesheet' media='print' onload=\"this.media='all'\"",
$html
);
}
/**
* Add preload link for Google Fonts
*/
public function preload() {
if ( empty( $this->options['href'] ) ) {
return;
}
?>
<link rel='preload' as='style' href='<?php echo esc_url( $this->options['href'] ); ?>'>
<?php
}
/**
* Add resource hints for Google Fonts
*/
public function resource_hints( $urls, $relation_type ) {
if ( 'preconnect' === $relation_type ) {
$urls[] = [
'href' => 'https://fonts.gstatic.com',
'crossorigin'
];
}
return $urls;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment