Skip to content

Instantly share code, notes, and snippets.

@alinademi
Forked from jhned/home-specific-enqueues.php
Created October 1, 2020 02:52
Show Gist options
  • Save alinademi/5cca98ed403b1ee57fece9c4921ca126 to your computer and use it in GitHub Desktop.
Save alinademi/5cca98ed403b1ee57fece9c4921ca126 to your computer and use it in GitHub Desktop.
Home Specific CSS
add_action( 'wp_enqueue_scripts', 'enqueue_scripts', 1 );
function enqueue_scripts() {
if ( is_front_page() ) {
// On the home page, enqueue the home CSS, and don't defer it.
// Include the full stylesheet as well, for UX CSS (e.g., :hover), but DO defer it with a filter on style_loader_tag.
wp_enqueue_style( 'site-screen-home-no-defer', get_template_directory_uri() . '/css/style.home.css', null, false, 'screen' );
wp_enqueue_style( 'site-screen', get_template_directory_uri() . '/css/style.css', null, false, 'screen' );
} else {
wp_enqueue_style( 'site-screen-no-defer', get_template_directory_uri() . '/css/style.css', null, false, 'screen' );
}
}
if ( ! is_admin() ) {
add_filter( 'style_loader_tag', 'filter_style_tag', 10, 4 );
}
function filter_style_tag( $tag, $handle, $href, $media ) {
// If the tag has "no-defer" in the handle, it won't be deferred.
if ( false === strpos( $handle, 'no-defer' ) ) {
// We use "prefetch" here instead of "preload." Preload forces the browser to download the file. Prefetch allows the page to load, then downloads it once the browser is idle.
// Prefetch, however, is notoriously not supported in Safari. Hence the "onload" attribute. This ensures that the stylesheet is still loaded once the page loads.
// Last but not least, we included a noscript tag. Just in case.
return '<link id="' . $handle . '-css" rel="prefetch" href="' . $href . '" as="style" onload="this.onload=null;this.rel=\'stylesheet\'" media="' . $media . '"><noscript><link rel="stylesheet" href="' . $href . '"></noscript>';
}
return $tag;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment