Skip to content

Instantly share code, notes, and snippets.

@iansvo
Created May 16, 2023 16:57
Show Gist options
  • Save iansvo/23111d71b060fb0adfe97ca2bd39f681 to your computer and use it in GitHub Desktop.
Save iansvo/23111d71b060fb0adfe97ca2bd39f681 to your computer and use it in GitHub Desktop.
Adds async and preload behavior to a given stylesheet in a WordPress theme. Opt-in only.
<?php
add_action( 'style_loader_tag', function ( string $tag, string $handle, string $href, string $media ) : string {
$allowlist = [ 'lwtd-style' ];
if ( !in_array( $handle, $allowlist, true ) ) {
return $tag;
}
$new_tag = new WP_HTML_Tag_Processor( $tag );
$fallback = '<noscript>' . $tag . '</noscript>';
$preload_tag = '<link rel="preload" href="' . $href . '" as="style">';
$new_tag->next_tag('link');
$new_tag->set_attribute('media', 'print');
$new_tag->set_attribute('onload', "this.media= '$media'");
return $preload_tag . $new_tag->get_updated_html() . $fallback;
}, 99, 4 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment