Skip to content

Instantly share code, notes, and snippets.

@qstudio
Last active September 27, 2020 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qstudio/b594d3d055d6ffbcb5e6fca076b1e2d9 to your computer and use it in GitHub Desktop.
Save qstudio/b594d3d055d6ffbcb5e6fca076b1e2d9 to your computer and use it in GitHub Desktop.
<?php
// hook into the style_loader_tag filter, but not in the admin ##
if ( ! \is_admin() ) {
\add_filter( 'style_loader_tag', 'q_style_loader_tag', 0, 4 );
}
// add the filter function - passing 4 params ##
/**
* Defer style asset enqueuing
*
* @param String $html The original enqueued <link rel="...> tag
* @param String $handle The registered unique name of the script
* @return String $href The asset file path with fragrments
* @return String $media A string reference to the css media type - i.e screen
* @return String $html The src <link rel="...> tag
*/
// only on the front-end
function q_style_loader_tag( $html, $handle, $href, $media ) {
// error_log( $html );
// error_log( $tag );
// error_log( $href );
// error_log( $handle );
// exclude files based on handle match -- controlled by passed filter ##
$avoid = \apply_filters( 'q/hook/wp_enqueue_style/avoid', $avoid );
// error_log( $avoid );
if (
in_array( $handle, $avoid )
){
error_log( 'Not deferring load of style: '.$handle );
return $html;
}
// skip asset via "__nodefer" in $html - normally appended to src url i.e. 'src.css?__nodefer' ##
if ( strpos( $html, '__nodefer') !== false ) {
error_log( 'Not deferring load of style: '.$handle );
return $html;
}
// check for passed query vars ##
$parts = parse_url( $href );
parse_str( $parts['query'], $query );
// get version fragment ##
$version = isset( $query['ver'] ) ? '?ver='.$query['ver'] : '' ;
// link to "media = 'null'" '.$media.' - onload swap to defined media type ##
$html = '<link rel="stylesheet" id="'.$handle.'" href="'.$href.$version.'" media="null" onload=\'if( media == "null" ) media="'.$media.'"\'>';
// add no JS backup ##
$html .= '<noscript><link rel="stylesheet" id="'.$handle.'" href="'.$href.$version.'" type="text/css" media="'.$media.'" /></noscript>';
// return html ##
return $html;
}
// example of how to add an asset to the avoid array via the filter ##
\add_filter( 'q/hook/wp_enqueue_style/avoid', function( $array ){
// add asset handles to skip ##
$skip = [
'acf-main', // main acf css file ##
];
$return = array_merge( $skip, $array );
// check ##
// error_log( $return );
// kick back to filter ##
return $return;
});
// example of how to avoid deferring css files when adding via wp_enqueue_style ##
\wp_register_style( 'unique-handle', 'path/to/file/index.css?__nodefer', '', '1.0.0' );
\wp_enqueue_style( 'unique-handle' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment