Skip to content

Instantly share code, notes, and snippets.

@adamsilverstein
Last active November 22, 2023 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adamsilverstein/cc8ebc44e3aed61aca82d71ce0225316 to your computer and use it in GitHub Desktop.
Save adamsilverstein/cc8ebc44e3aed61aca82d71ce0225316 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.
<?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