-
-
Save bryanwillis/af5fb7e699f30996dd2a to your computer and use it in GitHub Desktop.
Class that allows you to async and defer scripts in WordPress by adding data.
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 | |
class WP_Scholar_Defer_Scripts { | |
public static function initialize() { | |
add_filter( 'script_loader_tag', array( __CLASS__, 'defer_scripts' ), 10, 2 ); | |
add_filter( 'script_loader_tag', array( __CLASS__, 'async_scripts' ), 10, 2 ); | |
} | |
public static function defer_scripts( $tag, $handle ) { | |
global $wp_scripts; | |
if ( $wp_scripts->get_data( $handle, 'defer' ) ) { | |
$tag = str_replace( '></', ' defer></', $tag ); | |
} | |
return $tag; | |
} | |
public static function async_scripts( $tag, $handle ) { | |
global $wp_scripts; | |
if ( $wp_scripts->get_data( $handle, 'async' ) ) { | |
$tag = str_replace( '></', ' async></', $tag ); | |
} | |
return $tag; | |
} | |
} |
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 | |
add_action( 'login_enqueue_scripts', function () { | |
global $wp_scripts; | |
wp_enqueue_script( 'recaptcha', 'https://www.google.com/recaptcha/api.js' ); | |
$wp_scripts->add_data( 'recaptcha', 'async', true ); | |
$wp_scripts->add_data( 'recaptcha', 'defer', true ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment