Script Loader: Allow for wp_register_script() to be called after wp_enqueue_script().

When a plugin registers styles/scripts on `wp_enqueue_scripts` (as plugin authors are encouraged to do), and conditionally enqueues their script/style on `the_content` filter, things "just work". In block themes, `the_content` is run prior to the header being processed, which results in the above scenario failing.

This change makes a `wp_enqueue_script( 'example' ); wp_register_script( 'example' );` work, where as currently the enqueue silently fails (no "doing it wrong" message) and the following register has no impact. Scripts can therefore be enqueued and dequeued (by "handle") before they are registered.

Fixes #54529.

Built from https://develop.svn.wordpress.org/trunk@52338


git-svn-id: http://core.svn.wordpress.org/trunk@51930 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
audrasjb 2021-12-07 17:46:01 +00:00
parent 4f0c8ef665
commit cdafa716f7
2 changed files with 30 additions and 1 deletions

View File

@ -94,6 +94,15 @@ class WP_Dependencies {
*/
private $all_queued_deps;
/**
* List of assets enqueued before details were registered.
*
* @since 5.9.0
*
* @var array
*/
private $queued_before_register = array();
/**
* Processes the items and dependencies.
*
@ -248,6 +257,18 @@ class WP_Dependencies {
return false;
}
$this->registered[ $handle ] = new _WP_Dependency( $handle, $src, $deps, $ver, $args );
// If the item was enqueued before the details were registered, enqueue it now.
if ( array_key_exists( $handle, $this->queued_before_register ) ) {
if ( ! is_null( $this->queued_before_register[ $handle ] ) ) {
$this->enqueue( $handle . '?' . $this->queued_before_register[ $handle ] );
} else {
$this->enqueue( $handle );
}
unset( $this->queued_before_register[ $handle ] );
}
return true;
}
@ -334,6 +355,12 @@ class WP_Dependencies {
if ( isset( $handle[1] ) ) {
$this->args[ $handle[0] ] = $handle[1];
}
} else if ( ! isset( $this->registered[ $handle[0] ] ) ) {
$this->queued_before_register[ $handle[0] ] = null; // $args
if ( isset( $handle[1] ) ) {
$this->queued_before_register[ $handle[0] ] = $handle[1];
}
}
}
}
@ -360,6 +387,8 @@ class WP_Dependencies {
unset( $this->queue[ $key ] );
unset( $this->args[ $handle[0] ] );
} else if ( array_key_exists( $handle[0], $this->queued_before_register ) ) {
unset( $this->queued_before_register[ $handle[0] ] );
}
}
}

View File

@ -16,7 +16,7 @@
*
* @global string $wp_version
*/
$wp_version = '5.9-beta1-52337';
$wp_version = '5.9-beta1-52338';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.