-
-
Save WISHPRO/11ff43bfc282220772e1429d14edf1a2 to your computer and use it in GitHub Desktop.
Hook into `wp_enqueue_script` and defer all scripts using defer strategy from WordPress 6.3.
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 | |
/** | |
* Recursively add the defer strategy to a script and all its dependencies. | |
* | |
* @param string $handle The script handle. | |
* @return void | |
*/ | |
function recursively_add_defer_strategy( $handle ) { | |
wp_script_add_data( $handle, 'strategy', 'defer' ); | |
$script = wp_scripts()->registered[ $handle ]; | |
if ( ! empty( $script->deps ) ) { | |
foreach ( $script->deps as $dep ) { | |
recursively_add_defer_strategy( $dep ); | |
} | |
} | |
} | |
/** | |
* Hook into wp_enqueue_script and defer all scripts using defer strategy. | |
*/ | |
function add_defer_to_all_scripts() { | |
$scripts = wp_scripts()->registered; | |
// Iterate through all enqueued scripts and add the script strategy | |
foreach ( wp_scripts()->queue as $handle ) { | |
recursively_add_defer_strategy( $handle ); | |
} | |
} | |
add_action( 'wp_enqueue_scripts', 'add_defer_to_all_scripts', PHP_INT_MAX ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment