Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Created October 19, 2021 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sabrina-zeidan/b0e65d8d922cf0075c17577e2f6fcf81 to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/b0e65d8d922cf0075c17577e2f6fcf81 to your computer and use it in GitHub Desktop.
Defer all CSS in WordPress (with exclusions)
function sz_defer_all_css_but( $tag, $handle ) {
if (is_admin()) { return $tag; }
$handlestoexclude = [];
if ( !in_array($handle, $handlestoexclude ) ){
$dom = new \DOMDocument();
$dom->loadHTML($tag);
$csstag = $dom->getElementById($handle . '-css');
$csstag->setAttribute('media', 'print');
$csstag->setAttribute('onload', "this.media='all'");
$csstag->removeAttribute('type');
$tag = $dom->saveHTML($csstag);
}
return $tag;
}
add_filter( 'style_loader_tag', 'sz_defer_all_css_but', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment