Last active
May 12, 2023 10:24
-
-
Save ian-svoboda-prom/a2b7729afa3f63a002d0eef725f71743 to your computer and use it in GitHub Desktop.
Apply async/non-blocking loading to link tags in WordPress
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 | |
/** | |
* Inpspired by Scott Jehl: https://www.filamentgroup.com/lab/load-css-simpler/ | |
* | |
**/ | |
add_action( 'style_loader_tag', 'async_preload_stylesheets', 99, 4 ); | |
function async_preload_stylesheets( string $tag, string $handle, string $href, string $media ) : string { | |
// Add the stylesheet handles you want to load async | |
$allowlist = [ 'your-stylesheet-handle' ]; | |
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, modified link tag, and fallback | |
return $preload_tag . $new_tag->get_updated_html() . $fallback; | |
return $tag; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment