Last active
April 15, 2021 09:18
-
-
Save geoffreycrofte/4bfb156778e266e82a20efcd0206894a to your computer and use it in GitHub Desktop.
Defer specific CSS and JS with WordPress (for theme or plugins)
This file contains hidden or 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 | |
/** | |
* gc_my_scripts & gc_my_styles are two handles for enqueued CSS and JS. | |
* | |
* The CSS trick for defering CSS load and make it non blocking loading if offered by SitePoint | |
*/ | |
if ( ! function_exists( 'gc_defer_non_critical_css' ) ) { | |
/** | |
* Changes the LINK HTML tags to make it load async (deferred) | |
* | |
* @param string $tag The complete HTML LINK element. | |
* @param string $handle The unique ID of the CSS. | |
* @param string $href The URL of the CSS. | |
* @param string $media The original media attribute value. | |
* @return string The new LINK + NOSCRIPT TAG. | |
* @author Geoffrey Crofte | |
*/ | |
function gc_defer_non_critical_css( $tag, $handle, $href, $media ) { | |
if ( $handle === 'gc_my_styles' ) { | |
// Replace media value by media print and onload attributes. | |
$tag = str_replace( 'media=\''. $media .'\'', 'media="print" onload="this.onload=null;this.media=\'all\'"', $tag ); | |
// Adds a preload tags for the benefits of preloading, before the first <link> | |
$tag = '<link rel="preload" href="' . $href . '" as="style">' . $tag; | |
// Adds a noscript tags for fallback, after the <link>s | |
$tag .= '<noscript><link rel="stylesheet" media="' . $media . '" href="' . $href . '"></noscript>'; | |
} | |
return $tag; | |
} | |
add_filter( 'style_loader_tag', 'gc_defer_non_critical_css', 10, 4); | |
} | |
if ( ! function_exists( 'gc_asycn_javascript' ) ) { | |
/** | |
* Adds (Async too buggy) Defer Attributes to load scripts later and optimize performance. | |
* | |
* @param string $tag The complete HTML Script element. | |
* @param string $handle The unique ID of the script. | |
* @param string $src The URL of the script. | |
* | |
* @return string The modified HTML Script. | |
* @author Geoffrey Crofte | |
*/ | |
function gc_asycn_javascript($tag, $handle, $src) { | |
if ( $handle === 'gc_my_scripts' ) { | |
// If you need async, uncomment this | |
/*if ( false === stripos( $tag, 'async' ) ) { | |
$tag = str_replace(' src', ' async="async" src', $tag); | |
}*/ | |
if ( false === stripos( $tag, 'defer' ) ) { | |
$tag = str_replace('<script ', '<script defer ', $tag); | |
} | |
} | |
return $tag; | |
} | |
add_filter('script_loader_tag', 'gc_asycn_javascript', 10, 3); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment