Created
May 16, 2023 16:57
-
-
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.
This file contains 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 | |
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